import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import javax.print.DocFlavor.URL; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; @SuppressWarnings ( "all") // suppress all warnings public class Engine_GetRhino { public static void main(String[] args) { // TODO Auto-generated method stub // get the script engine ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine engine=sem.getEngineByName("javascript"); // define variables stored in the context engine engine.put("msg", "you are very good"); String str = "var user = {name: 'waibizi', age: 18, schools: [ 'Zhaoqing', 'Computer Science']};"; str += "print(user.name);"; // execute the script try { engine.eval(str); engine.eval("msg='you are very bad';"); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace (); } // Test output System.out.println(engine.get("msg")); try { // define the function engine.eval("function add(a,b){var sum = a + b; return sum;}"); engine.eval("function add1(){var sum = 123 + 321; return sum;}"); // function execution Invocable jsInvoke = (Invocable) engine; Object result = jsInvoke.invokeFunction ( "add", new Object [] {15,13}); // specifies the function assignment Object result1 = jsInvoke.invokeFunction ( "add1"); // specify the function assignment System.out.println(result); System.out.println(result1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace (); } try { // js import java package using java class // The following code is commented out JDK1.6, the first has been abandoned, did not see the comment below // String jsCode = "importPackage (java.util); var list = Arrays.asList ([\" Zhaoqing University \ "\" School of Computer Science \ ", \" Software Engineering \ "]);"; String jsCode = "var list = java.util.Arrays.asList ([\" Zhaoqing University \ "\" School of Computer Science \ ", \" Software Engineering \ "]);"; engine.eval(jsCode); List list = (List) engine.get("list"); for(int i=0;i<list.size();i++) { System.out.println(list.get(i)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace (); } try { java.net.URL url = Engine_GetRhino.class.getClassLoader().getResource("demo.js"); FileReader fr = new FileReader(url.getPath()); engine.eval(fr); fr.close (); // Since only a test, not so standardized. We have to use try catch finally the actual use! } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace (); } } }
a.js follows
function test(){ There are a = 666; print("invoke js file:"+a); } test();