目前还没有合适的解决方案,但我通过在 OpenNLP 中注册一个新的特性工厂来解决这个问题。GeneratorFactory
不幸的是,这需要通过反射访问 OpenNLP 类的私有部分。这是一个有效的解决方案。
首先,定义一个新类,命名为XmlDescriptorUtil
:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.featuregen.AdaptiveFeatureGenerator;
import opennlp.tools.util.featuregen.FeatureGeneratorResourceProvider;
import opennlp.tools.util.featuregen.GeneratorFactory;
import org.w3c.dom.Element;
public final class XmlDescriptorUtil {
private XmlDescriptorUtil(){};
public static abstract class XmlDescriptorFactory implements InvocationHandler
{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return create((Element)args[0], (FeatureGeneratorResourceProvider)args[1]);
}
public abstract AdaptiveFeatureGenerator create(Element generatorElement, FeatureGeneratorResourceProvider resourceManager)
throws InvalidFormatException;
}
public static void register(String name, XmlDescriptorFactory factory) throws Exception
{
Class<?> factoryInterface = Class.forName(GeneratorFactory.class.getName()+"$XmlFeatureGeneratorFactory");
Object proxy = Proxy.newProxyInstance(GeneratorFactory.class.getClassLoader(), new Class[]{factoryInterface}, factory);
registerByProxy(name, proxy);
}
private static void registerByProxy(String name, Object proxy) throws Exception
{
Field f = GeneratorFactory.class.getDeclaredField("factories");
f.setAccessible(true);
@SuppressWarnings("unchecked")
Map<String, Object> factories = (Map<String, Object>) f.get(null);
factories.put(name, proxy);
}
}
然后,创建一个实现公共接口的特征生成器工厂XmlDescriptorUtil$XmlDescriptorFactory
:
public static void main(String[] args) {
XmlDescriptorUtil.register("myCustom", new XmlDescriptorUtil.XmlDescriptorFactory() {
@Override
public AdaptiveFeatureGenerator create(Element generatorElement, FeatureGeneratorResourceProvider resourceManager) throws InvalidFormatException {
return new MyFeatureGenerator();
});
}
现在,特征生成器已准备就绪,可以在 XML 描述符中使用:
<generators>
<cache>
<generators>
...
<myCustom/>
</generators>
</cache>
</generators>
如果特征生成器需要参数,可以从generatorElement
工厂类中提取。