Java Reference
In-Depth Information
The following snippet of code creates an instance of the
JKScript
script engine using
JKScript
as its name. You can also use its other names such as
jks
and
jkscript
:
// Create the JKScript engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JKScript");
if (engine == null) {
System.out.println("JKScript engine is not available. " +
"Add jkscript.jar to CLASSPATH.");
}
else {
// Evaluate your JKScript
}
Listing 8-5 contains a program that uses the
JKScript
script engine to evaluate
different types of expressions. Expressions stored in
String
objects and files are executed.
Some expressions use numeric literals and some bind variables whose values are passed
in bindings in engine scope and global scope of the default
ScriptContext
of the engine.
Note that this program expects a file named
jkscript.txt
in the current directory that
contains an arithmetic expression that can be understood by the
JKScript
script engine.
If the script file does not exist, the program prints a message on the standard output with
the path of the expected script file. You may get a different output in the last line.
Listing 8-5.
Using the JKScript Script Engine
// JKScriptTest.java
package com.jdojo.script;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JKScriptTest {
public static void main(String[] args) throws FileNotFoundException,
IOException {
// Create JKScript engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JKScript");
Search WWH ::
Custom Search