我有一个Java HashMap,我已将其传递给脚本引擎。我想在处理条目时将其删除,因为我稍后会报告无效密钥。删除条目(delete testMap['key'];
)的明显常用方法无效。
如何让这个测试通过?
@Test
public void mapDelete() throws ScriptException{
Map<String,String> map = new HashMap<>(1);
map.put("key","value");
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("testMap", map);
engine.eval("delete testMap['key'];");
Assert.assertEquals (0, map.size());
}
答案 0 :(得分:3)
如果您知道自己有HashMap
,则可以在Nashorn
内使用Map API,即:
@Test
public void mapDelete() throws ScriptException {
Map<String,String> map = new HashMap<>(1);
map.put("key","value");
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("testMap", map);
engine.eval("testMap.remove('key');");
Assert.assertEquals (0, map.size());
}