In javax Importing maps in the scripting JavaScript environment
I'm in javax Some strange behaviors are seen in the scripting map implementation
The online example shows an example of adding a list in 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 use an operation similar to a map, you will see strange behavior On the one hand, if you try to iterate over map keys, for example
HashMap<String,Object> m = new HashMap<String,Object>(); jsEngine.put("map",m);
There is no way to get the map key – if you try to traverse the key, you will get the method name –
jsEngine.eval(" for (var k in m.keySet()){ println(k)};");
The result is:
notifyAll removeAll containsAll contains empty equals ...
In JS context, you can use m.get (key) to map values in the map, but you cannot use M [key] to process values. If the key does not exist, an error will be raised Can someone understand this behavior, or just break it? thank you.
Solution
for.. In JavaScript is different from everything in Java, even if they look similar For JavaScript iterates over attribute names in objects in JavaScript The method name is exposed to rhino as a property of the native Java HashMap object, just as you have the following JavaScript objects:
{ notifyAll:function(){},removeAll:function(){},containsAll:function(){},contains:function(){},empty:function(){},equals:function(){} }
My suggestion is to use set The toArray method converts the HashMap keyset to an array, or use set Iterator () gets the iterator This is a short rhino script that shows how to do this using the toArray method:
x=new java.util.HashMap(); x.put("foo","bar"); x.put("bat","bif"); x.put("barf","boo"); var keyArray = x.keySet().toArray(); for(var i=0,l = keyArray.length; i < l; i++){ var key = keyArray[i]; var value = x.get(key); print(value); }
Which outputs:
bif bar boo
Here is how to use set The iterator does the same thing:
x=new java.util.HashMap(); x.put("foo","boo"); var keyIter = x.keySet().iterator(); while(keyIter.hasNext()){ var key = keyIter.next() var value = x.get(key); print(value); }