Jump to content

  • Log In with Google      Sign In   
  • Create Account

Rhino JavaScript objects as Java objects


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 duktapeman90   Members   -  Reputation: 126

Like
0Likes
Like

Posted 30 April 2014 - 09:56 AM

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, 30 April 2014 - 12:07 PM.


Sponsor:

#2 TheChubu   Crossbones+   -  Reputation: 4420

Like
0Likes
Like

Posted 30 April 2014 - 03:46 PM

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 Making a Terrain Generator





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS