Categories:
Audio (13)
Biotech (29)
Bytecode (36)
Database (77)
Framework (7)
Game (7)
General (507)
Graphics (53)
I/O (35)
IDE (2)
JAR Tools (101)
JavaBeans (21)
JDBC (121)
JDK (426)
JSP (20)
Logging (108)
Mail (58)
Messaging (8)
Network (84)
PDF (97)
Report (7)
Scripting (84)
Security (32)
Server (121)
Servlet (26)
SOAP (24)
Testing (54)
Web (15)
XML (309)
Collections:
Other Resources:
RhinoSystemOut.java - Mapping Java Object to Rhino
How to map "System.out" object to Rhino JavaScript context, so I can use it in my JavaScript code?
✍: FYIcenter
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
2017-08-13, 2309🔥, 0💬
Popular Posts:
JDK 1.1 source code directory contains Java source code for JDK 1.1 core classes: "C:\fyicenter\jdk-...
Java Advanced Imaging (JAI) is a Java platform extension API that provides a set of object-oriented ...
JSP(tm) Standard Tag Library 1.0 implementation - Jakarta Taglibs hosts the Standard Taglib 1.0, an ...
JDK 11 jdk.rmic.jmod is the JMOD file for JDK 11 RMI (Remote Method Invocation) Compiler Tool tool, ...
How to download and install JDK (Java Development Kit) 5? If you want to write Java applications, yo...