Java Reference
In-Depth Information
Listing 12-7 contains the Java program that performs the following steps:
•
Loads the
point.js
script file that will load the definition of the
Point
constructor
Gets the reference of the
•
Point
constructor by calling
engine.
get("Point")
Creates two
•
Point
objects named
p1
and
p2
by calling the
newObject()
method on the
Point
constructor
Invokes the
•
callMember()
method on
p1
to invoke its
distance()
method to compute the distance between
p1
and
p2
•
Invokes the
callMember()
method on
p1
and
p2
to get their string
representation by calling their
toString()
method declared in
the
Point
constructor
•
Finally, prints the distance between the two points
Listing 12-7.
Creating Nashorn Objects in Java Code
// CreateScriptObject.java
package com.jdojo.script;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
public class CreateScriptObject {
public static void main(String[] args) {
// Construct the script file path
String scriptFileName = "point.js";
Path scriptPath = Paths.get(scriptFileName);
// Make sure the script file exists. If not, print the full
// path of the script file and terminate the program.
if (! Files.exists(scriptPath) ) {
System.out.println(scriptPath.toAbsolutePath() +
" does not exist.");
return;
}
// Get the Nashorn script engine
ScriptEngineManager manager = new ScriptEngineManager();
Search WWH ::
Custom Search