I'm seeing some odd behavior in the javax.scripting map implementation.
The online examples show an example of adding to a list within the js environment:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
List<String> namesList = new ArrayList<String>();
namesList.add("Jill");
namesList.add("Bob");
namesList.add("Laureen");
namesList.add("Ed");
jsEngine.put("namesListKey", namesList);
System.out.println("Executing in script environment...");
try
{
jsEngine.eval("var names = namesListKey.toArray();" + "for(x in names) {" + " println(names[x]);" + "}"
+ "namesListKey.add(\"Dana\");");
} catch (ScriptException ex)
{
ex.printStackTrace();
}
System.out.println(namesList);
However, if you try to do something similar with a map, you see odd behavior. For one thing, if you try to iterate through the map keys, e.g.
HashMap<String, Object> m = new HashMap<String, Object>();
jsEngine.put("map", m);
There's no way to obtain the map keys - if you try to iterate through the keys, you get method names-
jsEngine.eval(" for (var k in m.keySet()){ println(k)};");
results in :
notifyAll
removeAll
containsAll
contains
empty
equals
...
In the js context you can address values in the map with m.get(key)
but not with m[key]
, and if the key doesn't exist it throws an error. Can anyone shed some light on this behavior, or is it just broken? Thanks.