178 CHAPTER 9 SCRIPTING AND JSR 223
180 CHAPTER 9 SCRIPTING AND JSR 223 By itself, this doesn t make Invocable that great of an operation but it has a second side: its getInterface() method. With the getInterface() method, you can dynamically create new implementations of interfaces by defining the implementations of an interface s methods in the scripting language. Let s take this one a little more slowly by looking at a specific interface. The Runnable interface has one method: run(). If your scripting language has made a run() method invocable, you can acquire an instance of the Runnable interface from the Invocable engine. First, evaluate a no-argument run() method to make it invocable: engine.eval(”function run() {print(’wave’);}”); Next, associate it to an instance of the interface: Runnable runner = invokeEngine.getInterface(Runnable.class); You can now pass this Runnable object to a Thread constructor for execution: Thread t = new Thread(runner); t.start(); Listing 9-6 puts all these pieces together. There is an added Thread.join() call to ensure that the newly created thread finishes before the program exits. Listing 9-6. Using Invocable to Implement Interfaces import javax.script.*; public class InterfaceTest { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); try { engine.eval(”function run() {print(’wave’);}”); Invocable invokeEngine = (Invocable)engine; Runnable runner = invokeEngine.getInterface(Runnable.class); Thread t = new Thread(runner); t.start(); t.join(); } catch (InterruptedException e) {
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services