我像这样使用沙盒Nashorn:
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[]{"--no-java", "--no-syntax-extensions", "--optimistic-types=true", "--language=es6"},
null);
但是我想在我的JavaScript中使用单个特定的类。怎么做?
例如,我有一个课:
class MyClass
{
public void m1()
{
System.out.println("This is m1");
}
public void m2()
{
System.out.println("This is m2");
}
}
我想在脚本中使用它
let a=new MyClass();
a.m1();
a.m2();
怎么做?
谢谢
最佳答案
您可以使用Bindings
为ScriptEngine
提供java对象:
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class MyClass {
public static void main(String[] args) {
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[]{"--no-java", "--no-syntax-extensions", "--optimistic-types=true", "--language=es6"},
null);
Bindings bindings = engine.createBindings();
bindings.put("myclass", new MyClass());
engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
String code = "myclass.m1();";
try {
engine.eval(code, bindings);
} catch (ScriptException e) {
e.printStackTrace();
}
}
public void m1() {
System.out.println("This is m1");
}
public void m2(String str) {
System.out.println("This is m2 " + str);
}
public void m3(Class claz) {
System.out.println(claz);
}
}
或者如果真的需要在JS代码中实例化
MyClass
(可以与Java> = 9一起使用): Bindings bindings = engine.createBindings();
bindings.put("myclass", StaticClass.forClass(MyClass.class));
var code = "var a = new myclass(); a.m1();";
try {
engine.eval(code, bindings);
} catch (ScriptException e) {
e.printStackTrace();
}
关于java - 将Java类置于nashorn的全局范围内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61379933/