In JSR 223, there is an optional interface by the name javax.script.Invocable. If you are using a Script engine that supports this interface (for example, JavaScript reference engine in Mustang supports this interface), then you can call a specific script function from Java. For example, a specific script function may be called from an event handler in Java to implement handler in script.
Simple sample is as follows:
import javax.script.*;
public class Main {
public static void main(String[] args) {
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
// JavaScript code in a String
String script = "function hello(name) { print('Hello, ' + name); }";
// check whether this engine supports javax.script.Invocable interface
// Note that this is an optional interface -- script engines may choose
// to omit this!!
if (engine instanceof Invocable) {
// There is also a overload eval method that accepts
// arbitrary java.io.Reader object for script input
// instead of String as used here...
engine.eval(script);
Invocable inv = (Invocable) engine;
// call a global script function called
// "hello" passing an array of arguments
// here, we pass one argument 'Sundar'
inv.invoke("hello", new Object[]{"Sundar"});
// there is also another overload of 'invoke' method
// that can call a script method on a script object
// if the scripting language happens to be object based/oriented:
// inv.invoke(scriptObj, scriptMethod, arguments);
}
} catch (ScriptException exp) {
exp.printStackTrace();
} catch (NoSuchMethodException exp) {
// this exception will be thrown if there is no script
// function of name specified.
exp.printStackTrace();
}
}
}
Nothing like writing a "hello world" program with new Java APIs! A simple Java program to use JSR 223 (javax.script) API with Mustang is as follows:
//import package
import javax.script.*;
public class Main {
public static void main(String[] args) {
try {
// create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
// create script engine for JavaScript
ScriptEngine jsengine = manager.getEngineByName("js");
// evaluate JavaScript code from String
jsengine.eval("print('hello world')");
} catch (ScriptException se) {
// Handle script exception here..
// FIXME: do a better job here!
se.printStackTrace();
}
}
}