Java examples for Scripting:Run Script
Using Compiled Scripts
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;/*from w w w. j a v a2 s . com*/ } Compilable comp = (Compilable) engine; String script = "print(n1 + n2)"; CompiledScript cScript = comp.compile(script); // Store n1 and n2 script variables in a Bindings Bindings scriptParams = engine.createBindings(); scriptParams.put("n1", 2); scriptParams.put("n2", 3); cScript.eval(scriptParams); // Execute the script again with different values for n1 and n2 scriptParams.put("n1", 9); scriptParams.put("n2", 7); cScript.eval(scriptParams); } }