1)使用脚本语言的优势
Rapid turnaround, encouraging experimentation.
Changing the behavior of a running program.
Enabling customization by 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)重定向Input和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 with 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 method like 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)
在 http://www.mozilla.org/rhino/ 下载rhino:
把js.jar加入系统CLASSPATH中
可以以交互模式调用js解释器:
java org.mozilla.javascript.tools.shell.Main
java org.mozilla.javascript.tools.debugger.Main
8)相互调用
HelloWorld hello = new HelloWorld();
engine.put("script_hello", hello);
engine.eval("script_hello.sayHello()");
String script = "function say(first,second){ print(first +' '+ second+'//n'); }";
engine.eval(script);
Invocable inv = (Invocable) engine;
inv.invokeFunction("say", "Hello", "Tony");
script = "function max(first,second) "
+ "{ return (first > second) ?first:second;}";
engine.eval(script);
//js与java接口的调用
Object obj = inv.invokeFunction("max", "1", "0");