RhinoSystemOut.java - Mapping Java Object to Rhino

Q

How to map "System.out" object to Rhino JavaScript context, so I can use it in my JavaScript code?

✍: FYIcenter

A

If you want to map "System.out" object or any other objects to Rhino JavaScript context, 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. Call Context.javaToJS() method to wrap the System.out Java object or any object to a Rhino object, jsOut:

    Object jsOut = Context.javaToJS(System.out, s); 

3. Call ScriptableObject.putProperty() method to set the Rhino object as a variable, varOut, into the Rhino Scriptable scope object:

    ScriptableObject.putProperty(s, "varOut", jsOut); 

4. Use the variable, varOut, anywhere in your JavaScript code:

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

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;
import org.mozilla.javascript.ScriptableObject;

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

    Object jsOut = Context.javaToJS(System.out, s); 
    ScriptableObject.putProperty(s, "varOut", jsOut); 
    
    String js = "varOut.println('Hello world!')";
      c.evaluateString(s, js, null, 1, null);
   }
}

Compile and run the example program, RhinoSystemOut.java:

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

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

Hello world!

 

RhinoExportVar.java - Exporting Rhino Variable to Java

RhinoHello.java - Rhino JavaScript Hello Example

Using Rhino JavaScript Library in Java Programs

⇑⇑ FAQ for Rhino JavaScript Java Library

2017-08-13, 2179🔥, 0💬