178 CHAPTER 9 SCRIPTING AND JSR 223
178 CHAPTER 9 SCRIPTING AND JSR 223 The CompileTest example here just adds 1 to a counter variable stored in the bindings of the ScriptEngine. Since the script is evaluated three times, its final value is 3. > java CompileTest Counter: 1.0 Counter: 2.0 Counter: 3.0 Compiling scripts can also be done from files, or more specifically, from Reader strings. Compilation is most beneficial for both large code blocks and those that execute repeatedly. The Invocable Interface Invocable is another optional interface that a scripting engine can implement. An invocable engine supports the calling of functions scripted in that engine s language. Not only can you call functions directly, but you can also bind functions of the scripting language to interfaces in Java space. Once a method/function has been evaluated by the engine, it can be invoked via the invoke() method of Invocable assuming of course that the engine implements the interface. Invocable functions can also be passed parameters that don t have to come through bindings; just pass in the method name to be executed and its arguments. To demonstrate, Listing 9-5 takes the earlier string reversal example from Listing 9-3 and makes the reversal code an invocable function. Listing 9-5. Using Invocable to Reverse Strings import javax.script.*; import java.io.*; public class InvocableTest { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); if (args.length == 0) { System.err.println(”Please pass name(s) on command line”); System.exit(-1); }
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services