DroidOS
DroidOS

Reputation: 8880

Calling Java function from Rhino

Calling Javascript functions running inside Rhino from Java is easy enough - that after all is why Rhino was created. The thing I am having trouble establishing is this:

Just how this should be done is not too clear to me. From the searches I have done thus far it involves using ScriptableObject.putProperty to pass the Java class in question, Storage in my case to JavaScript. However, how this should be done and then how it should be used at the JS end leaves me rather confused.

I would be most grateful to anyone here who might be able to point me in the right direction

Upvotes: 3

Views: 3775

Answers (1)

DroidOS
DroidOS

Reputation: 8880

Given that Rhino has less than 100 followers here it should perhaps come as little surprise that this question was not answered. In the mean time I have managed to find the solution myself and it turns out to be very simple. I share it below for the benefit of anyone else running into this thread.

My Storage class is very simple. It goes something like this

public class Storage
{
 public static boolean haveFile(){}
 public static boolean readFromFile(String fname){}
 ...
} 

When I call Javascript from Java via Rhino I simply pass a new instance of the Storage class as the last of my function parameters

Context rhino = Context.enter();
Object[] functionParams = new Object[] {"Other parameters",new Storage()};
rhino.setOptimizationLevel(-1);
try 
{
 Scriptable scope = rhino.initStandardObjects();
 String rhinoLog = "var log = Packages.io.vec.ScriptAPI.log;";
 String code = /*Javascript code here* as shown separately below/;
 rhino.evaluateString(scope, rhinoLog + code, "ScriptAPI", 1, null);
 Function function = (Function) scope.get("jsFunction", scope);
 Object jsResult = function.call(rhino,scope,scope,functionParams);
}

where the Javascript code is

function jsFunction(a,s)
{
 //a - or a,b,c etc - here will be the "other" parameters
 //s - will be the instance of the Java side Storage class passed above
 //now you can do things like
 s.writeToFile('fileName','fileData');
 var fd = s.readFromFile('fileName');
 s.dropFile('fileName');
 ...
}

Upvotes: 3

Related Questions