简体   繁体   中英

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:

  • Context : I have a Phonegap CLI (v 6.3.3) Android project (API 19+) where I do a great deal of processing via loadable JavaScript running inside rhino
  • A Phonegap plugin - which I am creating at the same time as the actual Phonegap app - contains class called Storage which provides public, static, methods such as readFromFile(String fileName) , writeToFile(String fileName,String data) etc.
  • What I want to be able to do is to call Storage.readFromFile etc from my loaded JavaScript code in Rhino.

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

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');
 ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM