Java脚本教程 – Java编译脚本
脚本引擎允许以Java类的形式编译脚本,然后重复执行它。
以下代码检查脚本引擎是否实现了可编译
接口:
import javax.script.Compilable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); if (engine instanceof Compilable) { System.out.println("Script compilation is supported."); } else { System.out.println("Script compilation is not supported."); } } }
上面的代码生成以下结果。
例子
可编译
接口包含两个方法:
CompiledScript compile(String script) throws ScriptException CompiledScript compile(Reader script) throws ScriptException
要执行编译脚本,请从CompiledScript类调用以下eval()方法之一。
Object eval() throws ScriptException Object eval(Bindings bindings) throws ScriptException Object eval(ScriptContext context) throws ScriptException
以下代码显示了如何编译脚本并执行它。它使用不同的参数执行相同的编译脚本两次。
import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); if (!(engine instanceof Compilable)) { System.out.println("Script compilation not supported."); return; } Compilable comp = (Compilable) engine; CompiledScript cScript = comp.compile("print(n1 + n2)"); Bindings scriptParams = engine.createBindings(); scriptParams.put("n1", 2); scriptParams.put("n2", 3); cScript.eval(scriptParams); scriptParams.put("n1", 9); scriptParams.put("n2", 7); cScript.eval(scriptParams); } }
上面的代码生成以下结果。