6.游戏特别离不开脚本(4)-应该避免将集合框架对象传给JS

java map  传给 javascript 不是自动关联的,最好别传啊,遍历起来也麻烦(尽量避开集合框架吧),用数组或者自建一个对象。这里虽然有种方法:

// build a Map
Map<String, String> map = new HashMap<String, String>();
map.put("bye", "now");

// Convert it to a NativeObject (yes, this could have been done directly)
NativeObject nobj = new NativeObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
    nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
}

// Get Engine and place native object into the context
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
engine.put("map", nobj);

// Standard Javascript dot notation prints 'now' (as it should!)
engine.eval("println(map.bye);");
原文地址:https://www.cnblogs.com/booke/p/3202730.html