RhinoPoundToKilo.java - Exchange Data with Rhino Variables

Q

How to exchange data between Java objects and Rhino JavaScript variables?

✍: FYIcenter

A

Exchanging data between Java objects and Rhino JavaScript variables can be done in 2 ways:

1. Sending data from Java to JavaScript - Call Context.javaToJS() method first to convert a Java object to a Rhino object. Then call ScriptableObject.putProperty() method to assign the Rhino object to JavaScript variable:

      Double pound = Double.valueOf(args[0]);
	  Object jsP = Context.javaToJS(pound, s); 
	  ScriptableObject.putProperty(s, "p", jsP);

2. Sending data from JavaScript to Java - Call ScriptableObject.setProperty() method first to retrieve the JavaScript variable as a Rhino object. Then call Context.jsToJava() to convert the Rhino object to a Java object:

	  Object jsK = ScriptableObject.getProperty(s, "k");
	  Double kilo = (Double) Context.jsToJava(jsK, Double.class);

There is also a quick way to retrieve JavaScript variable by calling s.get() method:

      Object jsK = s.get("k", s); 
      double kilo = Context.toNumber(jsK);

Here is the entire example program, RhinoPoundToKilo, that shows how to exchange data between Java objects and Rhino JavaScript variables:

// 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;

public class RhinoPoundToKilo {
   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";
	  js += "var k = p2k(p);";

      Double pound = Double.valueOf(args[0]);
	  Object jsP = Context.javaToJS(pound, s); 
	  ScriptableObject.putProperty(s, "p", jsP);

      c.evaluateString(s, js, null, 1, null);
	  Object jsK = ScriptableObject.getProperty(s, "k");
	  Double kilo = (Double) Context.jsToJava(jsK, Double.class);

      System.out.println("Pound to Kilo conversion:"); 
      System.out.println("   Pound = "+pound); 
      System.out.println("   Kilo = "+kilo); 

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

Compile and run the example program, RhinoPoundToKilo.java:

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

>\fyicenter\jdk-1.8.0\bin\java -cp .;\fyicenter\rhino1_7R5\js.jar RhinoPoundToKilo 5.0

Pound to Kilo conversion:
   Pound = 5.0
   Kilo = 2.26796
   
JavaScript used:
function p2k(p) {
   return p*0.453592;
}
var k = p2k(p);

 

Using Rhino JavaScript Library in Java Programs

⇒⇒FAQ for Rhino JavaScript Java Library

2017-08-08, 147👍, 0💬