请尝试使用此代码,正常情况下它可以工作。
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);
问题出在脚本的第一行:
var HashMap<String,String> = Java.type('java.util.HashMap<String,String>()');
而不是
var HashMap = Java.type('java.util.HashMap');
但您也可以将映射注入脚本并在脚本上操作它,如下所示:
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);