如何从nashorn访问Java对象函数
作者:互联网
我想创建一个允许用户提供任意过滤器功能的接口,以处理Java应用程序中的记录.我决定为此使用Java脚本实用程序,特别是nashorn和JavaScript.
我的问题是,当我传递对象进行评估时,我得到TypeError:org.XXX.XXX.MyClass没有这样的函数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;
}
}
解决方法:
事实证明,nashorn无法访问在私有类(如示例中的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;
}
标签:nashorn,private-class,java 来源: https://codeday.me/bug/20191118/2025477.html