RhinoFunctionCall.java - Call JavaScript Function from Java

Q

How to call an JavaScript function from my Java code? I have Rhino 1.7R5 installed.

✍: FYIcenter

A

If you want to call an JavaScript function from my Java code, you can follow this tutorial:

1. Create a Context object and Scriptable scope object with an instance of ContextFactory:

	  ContextFactory f = new ContextFactory();
      Context c = f.enterContext();
	  Scriptable s = c.initStandardObjects();

2. Create a JavaScript code to define your function and get it evaluated:

	  String js = "function p2k(p) {\n";
	  js += "   return p*0.453592;\n";
      js += "}\n";
      c.evaluateString(s, js, null, 1, null);

3. Export the function from JavaScript to Java like any data object:

	  Object jsF = ScriptableObject.getProperty(s, "p2k");
	  Function p2k = (Function) Context.jsToJava(jsF, Function.class);

4. Call the call() on the org.mozilla.javascript.Function object. Then convert its returning object to the proper value:

      Object jsR = p2k.call(c, s, s, args);
	  Double kilo = (Double) Context.jsToJava(jsR, Double.class);

Here is the entire example program, RhinoFunctionCall, that shows how to define a function in JavaScript and run it from Java:

// Copyright (c) 2017 FYIcenter.com
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Function;

public class RhinoFunctionCall {
   public static void main(String[] args) throws Exception {
	  ContextFactory f = new ContextFactory();
      Context c = f.enterContext();
	  Scriptable s = c.initStandardObjects();

	  String js = "function p2k(p) {\n";
	  js += "   return p*0.453592;\n";
      js += "}\n";
      c.evaluateString(s, js, null, 1, null);

	  Object jsF = ScriptableObject.getProperty(s, "p2k");
	  Function p2k = (Function) Context.jsToJava(jsF, Function.class);

      Object jsR = p2k.call(c, s, s, args);
	  Double kilo = (Double) Context.jsToJava(jsR, Double.class);

      System.out.println("Pound to Kilo conversion:"); 
      System.out.println("   Pound = "+args[0]); 
      System.out.println("   Kilo = "+kilo); 

      System.out.println("JavaScript used:"); 
      System.out.println(js);    }
}

Compile and run the example program, RhinoFunctionCall.java:

>\fyicenter\jdk-1.8.0\bin\javac -cp \fyicenter\rhino1_7R5\js.jar RhinoFunctionCall.java

>\fyicenter\jdk-1.8.0\bin\java -cp .;\fyicenter\rhino1_7R5\js.jar RhinoFunctionCall 6.0

Pound to Kilo conversion:
   Pound = 6.0
   Kilo = 2.721552

JavaScript used:
function p2k(p) {
   return p*0.453592;
}

 

Using Rhino JavaScript Library in Java Programs

⇒⇒FAQ for Rhino JavaScript Java Library

2017-08-08, 159👍, 0💬