NullPointer
NullPointer

Reputation: 7368

How to use java object in JavaScript engine in java8

I want to use java object in javascript engine but not able to do and getting exception: javax.script.ScriptException: :1:11 Expected ; but found <

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object map = engine.eval("var HashMap<String,String> = Java.type('java.util.HashMap<String,String>()');" +
                      "var map = new HashMap();" +
                      "map.put('key1', 'value1');" +
                      "map.put('key2', 'value2');" +
                      "map.put('key3', 'value3');" +
                      "map");
            System.out.println(map);

Upvotes: 1

Views: 647

Answers (1)

Valentin Michalak
Valentin Michalak

Reputation: 2147

Try with this code, normally it works.

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" +
            "var map = new HashMap();" +
            "map.put('key1', 'value1');" +
            "map.put('key2', 'value2');" +
            "map.put('key3', 'value3');" +
            "map");
System.out.println(map);

The problem was in the first line of the script:

var HashMap<String,String> = Java.type('java.util.HashMap<String,String>()');

instead of

var HashMap = Java.type('java.util.HashMap');

But you also can inject a map to your script and manipulate it on the script like this:

Map<String, String> map = new HashMap<>();
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("map", map);
engine.eval("map.put('key1', 'value1');" +
            "map.put('key2', 'value2');" +
            "map.put('key3', 'value3');");
System.out.println(map);

Upvotes: 1

Related Questions