Accessing java Maps & Lists as JavaScript Objects in Rhino

我怕爱的太早我们不能终老 提交于 2020-01-12 22:09:03

问题


Is there a way to access Java Maps and Lists as JavaScript Objects in Rhino?

I have a Map which contains only other maps and lists of primitives and Strings, I'd like to pass this to a Rhino script and do stuff to it, and return the modified object back out to Java - but since they are java.util.Map and java.util.List Objects, I can't use 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 a Rhino-specific way to do this, or if there is some conversion/cast utility that will help. Commons BeanUtils is not sufficient, because to convert a Map to a bean (which can be accessed via associative array syntax), you must first create a class which has all of the named mutators/accessors. I won't know the structure of the object at runtime.


回答1:


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




回答2:


https://developer.mozilla.org/en/New_in_Rhino_1.7R3#JS.c2.a0Objects_implement_Java_collections claims that JS objects resp. arrays can now be cast to Map resp. List, but this does not seem like it would work for your use case.




回答3:


iterators seem to be the key!

if you want to iterate over all entries of a map, you could 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);
}



回答4:


I had a similar problem that may be useful. I tried created native rhino objects and copied data into them.



来源:https://stackoverflow.com/questions/6046482/accessing-java-maps-lists-as-javascript-objects-in-rhino

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!