[英]How to remove element from Java Map from within Nashorn JavaScript
I have a Java HashMap which I have passed to the script engine. 我有一个Java HashMap,我已经传递给脚本引擎。 I would like to remove entries as they are processed because I'm reporting invalid keys later. 我想在处理条目时将其删除,因为我稍后会报告无效密钥。 The apparent usual method for removing entries ( delete testMap['key'];
) has no effect. 删除条目的明显常用方法( delete testMap['key'];
)无效。
How do I make this test pass? 如何让这个测试通过?
@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());
}
If you know that you have an HashMap
, you can use its Map API within Nashorn
, ie: 如果你知道你有一个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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.