Sign in to follow this  

Rhino JavaScript objects as Java objects

This topic is 1358 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So I'm working on a game in Java (yup, one of those), and I want to script it using Mozilla Rhino, since I already know JavaScript well enough. I was wondering if there was anyway to convert an Rhino JavaScript object into an actual Java object, preferably implementing some sort of interface.

 

I know there's a way to do this with the javax.script JavaScript engine, but it's terribly slow compare to the standalone distribution of Rhino, so I'd prefer to do it that way.

 

Let me give an example in case I worded this poorly (I probably did). Suppose I have this JavaScript:

function getNumber(){
   return 5;
}

And I want to implement this interface:

public interface NumberGetter {
   public int getNumber();
}

Now, if I were to use the javax.script library, I could do something like this to get the results I want:

ScriptEngine engine = new ScriptEningeManager().getEngineByName("JavaScript");
engine.eval(new FileReader("data/scripts/script.js"));

Invocable inv = (Invocable) engine;
NumberGetter ng = inv.getInterface(NumberGetter.class);

System.out.println(ng.getNumber());

And that would output the number 5, like it should.

 

How would I go about doing that with the standalone distribution of Rhino, if it's even possible? My assumption would be something along the lines of this,

Context context = Context.enter();
Scriptable script = context.initStandardObjects;
context.evalateReader(script, new FileReader("data.scripts/script.js"), "script", 0, null);
NumberGetter ng = (BaseClass) Context.jsToJava(script, NumberGetter.class);

but that just lands me with an IllegalStateException.

Edited by duktapeman90

Share this post


Link to post
Share on other sites

I have no idea about Javascript, but I'd advise against using Rhino. Nashorn is the new JavaScript engine in Java, and its part of OpenJDK now, so if you have Java 8 installed, you have Nashorn installed. It should be faster too.

Share this post


Link to post
Share on other sites
Sign in to follow this