Roy Bean
Roy Bean

Reputation: 75

java Nashorn ReferenceError

I'm making some experiences with nashorn.

For that I made this simple code in java, where I want to use a custom Object that I defined.

       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)");

I returns the following error:

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

Now I google it and they say to use:

     load("nashorn:mozilla_compat.js");

but I'm a little confuse to where i put (or how to use) this load function?


UPDATE

to import class work with nashorn it's necessary make the call like this:

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

for some reason it wasn't obvious to me :P

Upvotes: 1

Views: 3999

Answers (2)

Beneko
Beneko

Reputation: 11

You should put load("nashorn:mozilla_compat.js"); in your javascript file or you can put this line engine.eval("load(\"nashorn:mozilla_compat.js\");"); in your java code.

Upvotes: 0

rmuller
rmuller

Reputation: 12849

Using Nashorn, you should use:

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

Now you can use your custom Java Class.

See this good introduction for more information: http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

Complete example:

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);
    }

}

Upvotes: 3

Related Questions