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_VERSIONhttp://saxon.sf.net/feature/traceExternalFunctions→Feature.TRACE_EXTERNAL_FUNCTIONShttp://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(); }
注意事项
- 反射方式需要处理
NoSuchFieldException、IllegalAccessException等异常,且性能略低于直接使用常量; - 确保使用的URI与SaxonPE 11中
Feature常量的getUri()返回值完全一致; - 泛型转换需要确保传入的
value类型与目标Feature的类型匹配,避免类型转换错误。
内容的提问来源于stack exchange,提问作者DJolley
相关产品推荐
相关产品推荐

