1 Advantages of using scripting language
Rapid turnaround, encouraging experimentation.
Changing the behavior of a running program.
Enabling customization by the program users.
2)
The site Http://scripting.dev.java.net provides engines for a wide range of scripting languages.
For example, to add support for Groovy, the class path should contain groovy/lib/*
(from http://groovy.codehaus.org) and Groovy-engine.jar (from Http://scripting.dev.java.net).
3)
Javax.script.ScriptEngineManager
Javax.script.ScriptEngineFactory
Javax.script.ScriptEngine
Javax.script.Invocable
Javax.script.CompiledScript
ScriptEngine engine = Manager.getenginebyname ("JavaScript");
Object result = Engine.eval (scriptstring);
Object result = engine.eval (reader);
Engine.put (k, 1728);
Object result = Engine.eval ("K + 1");
4 redirect Input and output
StringWriter writer = new StringWriter ();
Engine.getcontext (). Setwriter (New PrintWriter (writer, true));
5) calling scripting functions and Methods
To call a function, call the Invokefunction method and the function name, followed by the function parameters:
If (engine implements invocable)
((invocable) engine). Invokefunction ("Afunction", param1, param2);
If the scripting language is Object oriented, you call can a as this:
Code View:
((invocable) engine). InvokeMethod (Implicitparam, "Amethod", explicitParam1, EXPLICITPARAM2);
6) Compiling a Script
Reader reader = new FileReader ("Myscript.js");
Compiledscript script = null;
If (engine implements compilable)
Compiledscript script = ((compilable) engine). compile (reader);
if (script!= null)
Script.eval ();
Else
Engine.eval (reader);
7)
Download Rhino in http://www.mozilla.org/rhino/:
Adding Js.jar to the system classpath
You can invoke the JS interpreter in interactive mode:
Java Org.mozilla.javascript.tools.shell.Main
Java Org.mozilla.javascript.tools.debugger.Main
8) Call each other
HelloWorld Hello = new HelloWorld ();
Engine.put ("Script_hello", hello);
Engine.eval ("Script_hello.sayhello ()");
String script = "function say (First,second) {print (the ' + ' + second+ '//n ');}";
Engine.eval (script);
Invocable INV = (invocable) engine;
Inv.invokefunction ("Say", "Hello", "Tony");
Script = "function max (First,second)"
+ "{return (> Second) First:second;}";
Engine.eval (script);
JS and Java interface calls
Object obj = inv.invokefunction ("Max", "1", "0");