Java Nashorn将java类(非实例)暴露给javascript

时间:2015-06-19 19:36:08

标签: java nashorn clearscript

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

现在使用Java Nashorn这不起作用。我只能公开类的实例:factory.getBindings().put("Worker", new Worker());

有没有办法通过Nashorn将类类型暴露给javascript。

谢谢!

2 个答案:

答案 0 :(得分:3)

您的脚本可以通过完全限定的名称(如

)直接访问任何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"));
    }
}

希望这有帮助!

答案 1 :(得分:0)

如果您已经拥有要向脚本公开的类型的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"));
    }
}