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

杀马特。学长 韩版系。学妹 提交于 2019-12-10 11:19:22

问题


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.


回答1:


Unless you're stuck with older JDK (jdk7 or below) for some reason, I'd recommend moving to jdk8u. You've ES 5.1 compliant JS implementation (Nashorn) that is bundled with JDK8+.



来源:https://stackoverflow.com/questions/37357531/sun-org-mozilla-javascript-internal-nativeobject-vs-org-mozilla-javascript-nativ

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