即时通讯使用nashorn脚本引擎,并且JSObject接口有问题。
我创建了一个基类,通过成员的HashMap将功能手动添加到JSObject中:
public abstract class EngineObject extends AbstractJSObject {
private Map<String, Object> members;
public EngineObject() {
this.members = new HashMap<>();
}
public abstract String getName();
public void initialize(Engine engine) {
}
@Override
public Object getMember(String name) {
return this.members.get(name);
}
@Override
public void setMember(String name, Object value) {
this.members.put(name, value);
}
@Override
public boolean hasMember(String name) {
return this.members.containsKey(name);
}
@Override
public void removeMember(String name) {
this.members.remove(name);
}
}
public class MyObject extends EngineObject {
this.setMember("test", (Runnable) () -> {
System.out.println("Test");
});
}
//JavaScript - works
MyObject.test.run();
//JavaScript -- doesn't work
MyObject.test();
如何将功能添加到哈希图中,以将javascript识别为功能?
以及如何通过getMember(从HashMap)调用函数?
最佳答案
如“ aventurin”所述,您的想法是正确的-但您的代码不完整。简单的可运行示例:
import javax.script.*;
import jdk.nashorn.api.scripting.*;
public class Main {
public static void main(String[] args) throws Exception {
JSObject jsobj = new AbstractJSObject() {
@Override
public Object getMember(String name) {
// return a Runnable for "func"
if (name.equals("func")) {
return new Runnable() {
@Override
public void run() {
System.out.println("in run!");
}
};
}
return null;
}
};
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.put("obj", jsobj);
e.eval("obj.func()");
}
}
关于java - Java Nashorn JSObject设置函数作为成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35974089/