腳本引擎允許以Java類的形式編譯腳本,然后重復執(zhí)行它。
以下代碼檢查腳本引擎是否實現(xiàn)了可編譯
接口:
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."); } } }
上面的代碼生成以下結(jié)果。
可編譯
接口包含兩個方法:
CompiledScript compile(String script) throws ScriptException CompiledScript compile(Reader script) throws ScriptException
要執(zhí)行編譯腳本,請從CompiledScript類調(diào)用以下eval()方法之一。
Object eval() throws ScriptException Object eval(Bindings bindings) throws ScriptException Object eval(ScriptContext context) throws ScriptException
以下代碼顯示了如何編譯腳本并執(zhí)行它。它使用不同的參數(shù)執(zhí)行相同的編譯腳本兩次。
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); } }
上面的代碼生成以下結(jié)果。
更多建議: