Skip to main content
gamedev.net
🔒 Locked

Rhino JavaScript objects as Java objects

Started by duktapeman90 0 replies 5.6k views
Original Post
duktapeman90
duktapeman90

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.

TheChubu
TheChubu

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.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"   My journals: dustArtemis ECS framework and 

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.