我开始使用 Java 6 中的动态 rhinoscript 功能,供那些更可能了解 Javascript 而不是 Java 的客户使用。
将 Map(关联数组、javascript obj 等)传递到 Javascript 以便脚本编写者可以使用标准 Javascript 点符号来访问值的最佳方法是什么?
我目前正在将值的 java.util.Map 传递到脚本中,但是脚本编写者必须编写“map.get('mykey')”而不是“map.mykey”。
基本上,我想做与this question.相反的事情
最佳答案
我采用了 Java NativeObject 方法,这就是我所做的......
// 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);");
关于java - 如何将 Java Map 转换为基本的 Javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519399/