简体   繁体   中英

How to remove element from Java Map from within Nashorn JavaScript

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM