Java Reference
In-Depth Information
// Cast the engine reference to the Compilable type
Compilable comp = (Compilable)engine;
try {
// Compile a script
String script = "print(n1 + n2)";
CompiledScript cScript = comp.compile(script);
// Store n1 and n2 script variables in a Bindings
Bindings scriptParams = engine.createBindings();
scriptParams.put("n1", 2);
scriptParams.put("n2", 3);
cScript.eval(scriptParams);
// Execute the script again with different values
// for n1 and n2
scriptParams.put("n1", 9);
scriptParams.put("n2", 7);
cScript.eval(scriptParams);
}
catch (ScriptException e) {
e.printStackTrace();
}
}
}
5
16
Summary
The Java Scripting API supports invoking procedures, functions, and methods
written in a scripting language directly from Java. This is made possible through the
Invocable
interface. If a script engine supports procedure invocation, it implements the
Invocable
interface. Nashorn engine supports procedure invocation. The procedure
being invoked may be implemented as top-level functions or methods of an object.
The
invokeFunction()
method of the
Invocable
interface is used to invoke top-level
functions in scripts. The
invokeMethod()
method of the
Invocable
interface is used to
invoke a method of an object. The top-level functions and the objects whose methods are
invoked must be evaluated by the engine before invoking them.
The Java Script API also lets you implement Java interfaces in scripting languages.
The methods of a Java interface may be implemented as top-level functions or methods
of an object. The
getInterface()
method of the
Invocable
interface is used to get the
implementation of a Java interface.
Search WWH ::
Custom Search