I have a Java HashMap which I have passed to the script engine. 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.
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:
@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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.