java Nashorn ReferenceError

时间:2017-11-07 15:45:59

标签: java nashorn

我正在与nashorn合作。

为此,我在java中创建了这个简单的代码,我想使用我定义的自定义对象。

       ScriptEngine engine = new 
       ScriptEngineManager().getEngineByName("javascript");
       System.out.println("engine = " + engine.getClass().getName().toString());

       engine.put("id", "2");
       System.out.println("id = " + engine.eval("id"));

       Object person = engine.eval("importClass(Data.com.personal.Person)");

我返回以下错误:

        Exception in thread "main" javax.script.ScriptException: ReferenceError: "importClass" is not defined in <eval> at line number 1

现在我谷歌了,他们说要使用:

     load("nashorn:mozilla_compat.js");

但是我对这个加载函数放置(或如何使用)的位置有点迷惑?

更新

使用nashorn导入课堂作业,必须按照以下方式拨打电话:

    engine.eval("importClass(com.personal.Person)");

出于某种原因,这对我来说并不明显:P

1 个答案:

答案 0 :(得分:2)

使用Nashorn,你应该使用:

var MyJavaClass = Java.type('my.package.MyJavaClass');

现在您可以使用自定义Java类。

有关详细信息,请参阅此简介:http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

完整示例:

public final class NashornTest {

    // Class can even be inner class. Must be public however!
    public static class MyData {

        private int id;
        private String name;

        public MyData(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return String.format("MyData[%d, %s]", id, name);
        }

    }

    @Test
    public void test() throws ScriptException {
        final ScriptEngineManager sem = new ScriptEngineManager();
        final ScriptEngine se = sem.getEngineByName("javascript");

        Object obj = se.eval(
            "var MyJavaData = Java.type('test.el.NashornTest$MyData');" +
            "new MyJavaData(42, 'The usual number');");

        // prints MyData[42, The usual number]
        System.out.println(obj);
    }

}