You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SaxonPE 11如何替代已移除的byName方法通过名称获取配置Feature?

SaxonPE 11 替代 Feature.byName() 的方案

从SaxonPE 9/10升级到11后,net.sf.saxon.lib.Feature<T>.byName(String name)方法被移除,官方未明确说明移除原因,但可以通过以下两种方式替代原有功能,同时规避弃用的setConfigurationProperty(String name, Object value)接口:

方案一:直接使用Feature类的静态常量(推荐)

SaxonPE 11的Feature类将所有配置项都定义为类型安全的静态常量,这是官方推荐的用法,比原字符串查找方式更可靠。

以设置xsltVersion为例,替换后的代码如下:

import net.sf.saxon.lib.Feature;
import net.sf.saxon.s9api.Processor;

Processor processor = new Processor(false);
processor.setConfigurationProperty(Feature.XSLT_VERSION, "3.0");

常用配置项对应的常量示例:

  • http://saxon.sf.net/feature/xsltVersion → Feature.XSLT_VERSION
  • http://saxon.sf.net/feature/traceExternalFunctions → Feature.TRACE_EXTERNAL_FUNCTIONS
  • http://saxon.sf.net/feature/allowExternalFunctions → Feature.ALLOW_EXTERNAL_FUNCTIONS

方案二:通过反射动态匹配URI(适配动态配置场景)

如果你的业务需要从外部配置(如配置文件)读取URI名称来动态设置配置,可以通过反射遍历Feature类的静态字段,匹配对应的URI获取Feature实例:

import net.sf.saxon.lib.Feature;
import java.lang.reflect.Field;

public static <T> Feature<T> getFeatureByName(String uri) throws Exception {
    // 遍历Feature类的所有静态字段
    for (Field field : Feature.class.getDeclaredFields()) {
        if (field.getType() == Feature.class) {
            Feature<?> feature = (Feature<?>) field.get(null);
            // 匹配目标URI
            if (uri.equals(feature.getUri())) {
                return (Feature<T>) feature;
            }
        }
    }
    throw new IllegalArgumentException("No feature found with URI: " + uri);
}

使用该工具方法的示例:

String name = "http://saxon.sf.net/feature/xsltVersion";
String value = "3.0";

try {
    Feature<String> feature = getFeatureByName(name);
    processor.setConfigurationProperty(feature, value);
} catch (Exception e) {
    // 处理异常(如URI不存在、反射权限问题等)
    e.printStackTrace();
}

注意事项

  1. 反射方式需要处理NoSuchFieldException、IllegalAccessException等异常,且性能略低于直接使用常量;
  2. 确保使用的URI与SaxonPE 11中Feature常量的getUri()返回值完全一致;
  3. 泛型转换需要确保传入的value类型与目标Feature的类型匹配,避免类型转换错误。

内容的提问来源于stack exchange,提问作者DJolley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:58:23