我想使用Java对象new Train()作为参数传递给JavaScript函数,下面是
public void execute() {
File script = new File("/Test.js");
ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js");
try {
engine.eval(new FileReader(script));
Invocable invocable = (Invocable)engine;
Object result = invocable.invokeFunction("fun1", new Train());
System.out.println(result);
} catch(Exception e) {
e.printStackTrace();
}
}public class Train {
private double speed = 0.0D;
public Train() {
this.speed = 10.5D;
}
public double getSpeed() {
return this.speed;
}
}JavaScript代码
var fun1 = function test(train) {
print(train.getSpeed());
return train.getSpeed();
}现在,它将这个错误放在控制台中。
[16:56:42] [INFO]: [STDERR]: javax.script.ScriptException: org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (getSpeed) on ScriptExecutor$Train@429b2a7b failed due to: Unknown identifier: getSpeed [16:56:42] [INFO]: [STDERR]: at com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.toScriptException(GraalJSScriptEngine.java:483) [16:56:42] [INFO]: [STDERR]: at com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.invokeFunction(GraalJSScriptEngine.java:558)
有什么办法让这件事成功吗?
发布于 2022-01-13 01:54:57
默认情况下,GraalJS (和一般的GraalVM )具有严格的安全/访问控制。GraalJS没有将Train实例上的getSpeed() (或任何其他字段或方法)公开给JavaScript。
可以使用配置设置打开对所有主机字段/方法的访问:
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("polyglot.js.allowHostAccess", true);或者通过在getSpeed()中装饰Train,在更细粒度的级别上启用它。
import org.graalvm.polyglot.HostAccess;
// ...
@HostAccess.Export
public double getSpeed() {
return this.speed;
}https://stackoverflow.com/questions/70689954
复制相似问题