我想创建一个接口,允许用户提供任意过滤器函数来处理Java应用程序中的记录。我决定使用Java Scripting实用程序,特别是nashorn和JavaScript。
我的问题是,当我传入对象进行评估时,我得到TypeError: org.XXX.XXX.MyClass has no such function xxx ...
public class FilterClass{
ScriptEngine engine;
Invocable inv;
public FilterClass(File file){
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript");
engine.eval(new FileReader(file));
inv = (Invocable) engine;
}
public boolean passes(MyObject object){
Object result = inv.invokeFunction("passes", object);
return (Boolean) result;
}
}
制作MyObject的对象工厂定义
public class MyObjectFactory{
private class MyObject{
private final int myint;
public MyObject(int i){
myint = i;
}
public int getValue(){
return myint;
}
}
public MyObject makeObject(int i){
return new MyObject(i);
}
}
javascript文件
function passes(o){
if(o.getValue() > 10){
return true;
} else {
return false;
}
}
答案 0 :(得分:3)
事实证明,nashorn无法访问private
类中定义的函数,例如示例中的MyObject类。
不想公开我的嵌套类,所以我最后围绕它编写了一个包装类来公开MyObject字段:
public class MyObjectWrapper{
private final MyObject myobject;
public MyObjectWrapper(MyObject o){
myobject = o;
}
public int getValue(){
return myobject.getValue();
}
}
然后我可以通过包装来访问这些函数:
public boolean passes(MyObject object){
Object result = inv.invokeFunction("passes", new MyObjectWrapper(object));
return (Boolean) result;
}