RhinoExportVar.java - Exporting Rhino Variable to Java

Q

How to export variable from Rhino JavaScript context to a Java object?

✍: FYIcenter

A

If you want to export variable from Rhino JavaScript context to a Java object, 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. Run the JavaScript code to set the JavaScript variable, str:

    String js = "var str = 'Hello world!'";
      c.evaluateString(s, js, null, 1, null);

3. Call get() method on the Scriptable scope object to export the variable, str, to a Java object, jsObj:

      Object jsObj = s.get("str", s); 

4. Call Context.toString() method to cast the Java object a string:

      System.out.println(Context.toString(jsObj)); 

Here is the entire example program, RhinoSystemOut, that maps System.out from Java as varOut in JavaScript:

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

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

    String js = "var str = 'Hello world!'";
      c.evaluateString(s, js, null, 1, null);

      Object jsObj = s.get("str", s); 
      System.out.println(Context.toString(jsObj)); 
   }
}

Compile and run the example program, RhinoExportVar.java:

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

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

Hello world!

 

RhinoPoundToKilo.java - Exchange Data with Rhino Variables

RhinoSystemOut.java - Mapping Java Object to Rhino

Using Rhino JavaScript Library in Java Programs

⇑⇑ FAQ for Rhino JavaScript Java Library

2017-08-08, 2268🔥, 0💬