gpt4 book ai didi

Java Nashorn JSObject 将函数设置为成员

转载 作者:行者123 更新时间:2023-12-02 03:49:54 26 4
gpt4 key购买 nike

我正在使用 nashorn 脚本引擎,并且 JSObject 接口(interface)有问题。我创建了一个基类,通过成员的 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();

如何将函数添加到 HashMap 中,以便 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 Nashorn JSObject 将函数设置为成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35974089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com