sun.org.mozilla.javascript.internal.NativeObject vs org.mozilla.javascript.NativeObject
Asked Answered
P

1

2

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.

Powerless answered 21/5, 2016 at 0:6 Comment(5)
You probably have to use the engine from your Rhino jar file as well if you want to use engine-specific interfaces.Erickson
@Erickson I am not following, can you paste a little code ?Powerless
If you load it via ScriptEngineManager 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-modulesErickson
This may also work: https://mcmap.net/q/753310/-can-nashorn-startup-slowness-be-overcome Then you can request getEngineByName("rhino17R5").Erickson
@Thino thank you so much, this thread works perfect https://mcmap.net/q/753310/-can-nashorn-startup-slowness-be-overcomePowerless
T
0

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+.

Tarsus answered 21/5, 2016 at 14:33 Comment(1)
If I can move over, then I won't need to ask here.Powerless

© 2022 - 2024 — McMap. All rights reserved.