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"?
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.
engine
from your Rhino jar file as well if you want to use engine-specific interfaces. – EricksonScriptEngineManager
you will get the version in the JDK (sun.org.mozilla
). If you want to use Rhino from your JAR file, load it with the native Rhino API instead: https://mcmap.net/q/753309/-java-7-rhino-1-7r3-support-for-commonjs-modules – EricksongetEngineByName("rhino17R5")
. – Erickson