ScriptEngine
可以在 String
和java.io.Reader中執(zhí)行腳本。
通過使用Reader,我們可以在網(wǎng)絡(luò)或文件中執(zhí)行腳本。
ScriptEngine接口的eval()方法具有以下重載版本。
Object eval(String script) Object eval(Reader reader) Object eval(String script, Bindings bindings) Object eval(Reader reader, Bindings bindings) Object eval(String script, ScriptContext context) Object eval(Reader reader, ScriptContext context)
以下代碼顯示如何運(yùn)行從.js文件存儲(chǔ)的Javascript腳本代碼。
名為helloscript.js的.js文件的內(nèi)容如下所示。
// Print a message print("Hello from JavaScript!");
這里是運(yùn)行腳本的代碼。
import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) { String scriptFileName = "c:/test.js"; Path scriptPath = Paths.get(scriptFileName); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); try { Reader scriptReader = Files.newBufferedReader(scriptPath); engine.eval(scriptReader); } catch (IOException | ScriptException e) { e.printStackTrace(); } } }
上面的代碼生成以下結(jié)果。
ScriptEngine
中的 eval()
方法以對(duì)象形式返回腳本中的最后一個(gè)值。
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Object result = null; result = engine.eval("1 + 2;"); System.out.println(result); result = engine.eval("1 + 2; 3 + 4;"); System.out.println(result); result = engine.eval("1 + 2; 3 + 4; var v = 5; v = 6;"); System.out.println(result); result = engine.eval("1 + 2; 3 + 4; var v = 5;"); System.out.println(result); result = engine.eval("print(1 + 2)"); System.out.println(result); } }
上面的代碼生成以下結(jié)果。
以下代碼顯示了如何將Result對(duì)象傳遞到使用值填充Result對(duì)象的腳本。
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { private int val = -1; public void setValue(int x) { val = x; } public int getValue() { return val; } public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Main result = new Main(); engine.put("result", result); String script = "3 + 4; result.setValue(1);"; engine.eval(script); int returnedValue = result.getValue(); System.out.println("Returned value is " + returnedValue); } }
上面的代碼生成以下結(jié)果。
更多建議: