Access Java Maps and Lists as JavaScript Objects in Rhino

Is there a way to access Java maps and lists as JavaScript objects in Rhino?

I have a map that contains only other maps and lists of primitives and strings, I would like to pass this Rhino script and make stuff for it and return the modified object back to Java, but since it is java.util.Map and java.util.List Objects, I can’t use the standard JavaScript associative array syntax. ie: fooMap.get("keyName") will work, but fooMap.keyName and fooMap["keyName"] will not.

I don’t know if there is an Rhino-specific way to do this, or if there is some kind of conversion / casting utility that will help. Commons BeanUtils is not enough, because to convert a map to a bean (which can be accessed through the associative array syntax), you must first create a class that has all the mutators / accessors named. I will not know the structure of the object at runtime.

+6
source share
4 answers

Take a look at RingoJS. It has convenient list wrappers and maps for Rhino, such as this

+2
source

https://developer.mozilla.org/en/New_in_Rhino_1.7R3#JS.c2.a0Objects_implement_Java_collections claims to be JS objects accordingly. arrays can now be dropped to Map respectively. List , but it doesn't look like this will work for your use case.

+1
source
Iterators

seem key!

if you want to iterate over all the map entries, you can do the following

Java

 //pass the map and map.keySet().iterator() to the javascript Object wrappedParameterMap = Context.javaToJS(parameterMap, scope); ScriptableObject.putProperty(scope, "parameterMap", wrappedParameterMap); Object wrappedParameterNames = Context.javaToJS(parameterMap.keySet().iterator(), scope); ScriptableObject.putProperty(scope, "parameterNames", wrappedParameterNames); 

JAVASCRIPT

 while(parameterNames.hasNext()) { key = parameterNames.next(); value = parameterMap.get(key); } 
+1
source

I had a similar problem that might be helpful. I tried to create native rhino objects and copy the data into them.

0
source

Source: https://habr.com/ru/post/888427/


All Articles