Java Nashorn 将 java 类(不是实例)公开给 javascript



我用ClearScript.NET将类暴露给Javascript。我用它来公开类(而不是类的实例给 JS):engine.AddHostType("Worker", typeof(Worker));所以我可以使用 var x = new Worker(); In javascript ;

现在在 Java Nashorn中,这是行不通的。我只能像这样公开类的实例:factory.getBindings().put("Worker", new Worker());

有没有办法使用 Nashorn 将类类型公开给 javascript。

谢谢!

您的脚本可以通过完全限定名直接访问任何 Java 类,例如

var Vector = Java.type("java.util.Vector");
// or equivalently:
var Vector = java.util.Vector;
// Java.type is better as it throws exception if class is not found

如果您不希望脚本直接引用您的 Java 类,或者您希望提供不同的名称,您可以执行以下操作:

import javax.script.*;
public class Main {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine e = m.getEngineByName("nashorn");
        // eval "java.util.Vector" to get "type" object and then
        // assign that to a global variable.
        e.put("Vec", e.eval("java.util.Vector"));
        // Script can now use "Vec" as though it is a script constructor
        System.out.println(e.eval("v = new Vec(); v.add('hello'); v"));
    }
}

希望这有帮助!

如果您已经有一个要向脚本公开的类型的 java.lang.Class 对象,则可以执行以下操作:

import javax.script.*;
import java.util.Vector;
public class Main {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine e = m.getEngineByName("nashorn");
        // expose a java.lang.Class object to script
        e.put("Vec", Vector.class);
        // script can use "static" property to get "type" represented
        // by that Class object.
        System.out.println(e.eval("v = new Vec.static(); v.add('hello'); v"));
    }
}

相关内容

  • 没有找到相关文章

最新更新