sun.org.mozilla.javascript.internal.NativeObject vs org.mozilla.javascript.NativeObject

81 views
Skip to first unread message

Siqi Chen

unread,
May 20, 2016, 8:00:35 PM5/20/16
to mozilla-rhino
I am really stuck at this now..

Essentially I have a Java Map, which I would like to pass it to a Javascript Code, so that in my JS code I can use dot notation to refer the keys in this Map. ( I know I can serialize the map into JSON and deserialize it back and pass it into JS, but I don't like that ) I have this piece of the unit code 


@Test
public void mapToJsTest() throws Exception{
Map m = Maps.newHashMap();
m.put("name", "john");

NativeObject nobj = new NativeObject();
for (Object k : m.keySet()) {
nobj.defineProperty((String)k, m.get(k), NativeObject.READONLY);
}

engine.eval("function test(obj){ return obj.name;}");
Object obj = ((Invocable)engine).invokeFunction("test", nobj);

Assert.assertEquals(obj, "john");
}



If I am using 
org.mozilla.javascript.NativeObject 
then the test won't pass,

However, if I am using 
sun.org.mozilla.javascript.internal.NativeObject
then the test will pass.

However, we all know that we shouldn't rely on these internal classes, and when I deploy my code on the server side, trying to access
this internal class will cause other problems.

So how do I achieve this with just "org.mozilla.javascript.NativeObject"?


Thanks
Siqi

Siqi Chen

unread,
May 20, 2016, 9:00:56 PM5/20/16
to mozilla-rhino
BTW, I am using Rhino

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

For Nashorn, it is much easier, I can pass Map directly into JS code.
Reply all
Reply to author
Forward
0 new messages