分享

java执行JavaScript代码

 muyable 2015-04-08
学习资料http://jnotnull./blog/262384

Java代码  收藏代码
  1. import java.util.ArrayList;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5. import java.util.Set;  
  6. import java.util.Map.Entry;  
  7.   
  8. import javax.script.Invocable;  
  9. import javax.script.ScriptEngine;  
  10. import javax.script.ScriptEngineManager;  
  11. import javax.script.ScriptException;  
  12.   
  13. import sun.org.mozilla.javascript.internal.NativeArray;  
  14. import sun.org.mozilla.javascript.internal.NativeObject;  
  15.   
  16. public class TestScript {  
  17.     public static void main(String[] args) throws Exception {  
  18.         ScriptEngineManager factory = new ScriptEngineManager();  
  19.         ScriptEngine engine = factory.getEngineByName("JavaScript");  
  20.         // engine.eval("print('hello')");  
  21.         // testScriptVariables(engine);// 演示如何暴露Java对象为脚本语言的全局变量  
  22.         // testInvokeScriptMethod(engine);// 演示如何在Java中调用脚本语言的方法  
  23.         // testScriptInterface(engine);// 演示脚本语言如何实现Java的接口  
  24.         // testUsingJDKClasses(engine);// 演示脚本语言如何使用JDK平台下的类  
  25.   
  26.         test(engine);  
  27.     }  
  28.   
  29.     public static void testScriptVariables(ScriptEngine engine)  
  30.             throws ScriptException {  
  31.         Map<String, Object> map = new HashMap<String, Object>();  
  32.   
  33.         engine.put("map", map);  
  34.         engine.eval("map.put('s',new Date);");  
  35.         System.out.println(map.get("s").getClass());  
  36.     }  
  37.   
  38.     public static void testInvokeScriptMethod(ScriptEngine engine)  
  39.             throws Exception {  
  40.         String script = "function hello(name) { return 'Hello,' + name;}";  
  41.         engine.eval(script);  
  42.         Invocable inv = (Invocable) engine;  
  43.         String res = (String) inv.invokeFunction("hello""Scripting");  
  44.         System.out.println("res:" + res);  
  45.     }  
  46.   
  47.     public static void testScriptInterface(ScriptEngine engine)  
  48.             throws ScriptException {  
  49.         String script = "var obj = new Object();obj.run = function() { println('run method called');}";  
  50.         engine.eval(script);  
  51.         Object obj = engine.get("obj");  
  52.         Invocable inv = (Invocable) engine;  
  53.         Runnable r = inv.getInterface(obj, Runnable.class);  
  54.         Thread th = new Thread(r);  
  55.         th.start();  
  56.     }  
  57.   
  58.     public static void testUsingJDKClasses(ScriptEngine engine)  
  59.             throws Exception {  
  60.         // Packages是脚本语言里的一个全局变量,专用于访问JDK的package  
  61.         // String js = "function doSwing(t){var f=new  
  62.         // Packages.javax.swing.JFrame(t);f.setSize(400,300);f.setVisible(true);}";  
  63.         String js = "function doSwing(t){var f=Packages.java.util.UUID.randomUUID();print(f)}";  
  64.         engine.eval(js);  
  65.         Invocable inv = (Invocable) engine;  
  66.         inv.invokeFunction("doSwing""Scripting Swing");  
  67.     }  
  68.   
  69.     /** 
  70.      * 我能想到的应用场景,将前台传过来的json数组构造成java的List<Map<String, 
  71.      * Object>>,然后就可以随心所欲的使用该list了 当然可以使用第三方jar采用json to 
  72.      * bean的方式,而且这种方案更优雅,但是需要引入第三方库 
  73.      *  
  74.      * @throws NoSuchMethodException 
  75.      * @throws ScriptException 
  76.      */  
  77.   
  78.     public static void test(ScriptEngine engine) throws ScriptException,  
  79.             NoSuchMethodException {  
  80.   
  81.         // String json =  
  82.         // "{'key1':'a','son':{'dd':'dd','a':8},'ran':Math.random()},{'key3':'xor'}";  
  83.         String json = "{'key1':'a','son':[{'dd':'dd'},{'dd1':'dd1'}],'ran':Math.random()},{'key3':'xor'}";  
  84.         NativeArray json2array = json2array(engine, "[" + json + "]");  
  85.         List<Map<String, Object>> list = array2list(engine, json2array);  
  86.         System.out.println(list);  
  87.   
  88.     }  
  89.   
  90.     public static NativeArray json2array(ScriptEngine engine, String json)  
  91.             throws ScriptException, NoSuchMethodException {  
  92.   
  93.         String script = "function hello() { return " + json + ";}";  
  94.         engine.eval(script);  
  95.         Invocable inv = (Invocable) engine;  
  96.         Object obj = inv.invokeFunction("hello");  
  97.   
  98.         // System.out.println(obj);  
  99.         return (NativeArray) obj;  
  100.   
  101.     }  
  102.   
  103.     public static List<Map<String, Object>> array2list(ScriptEngine engine,  
  104.             NativeArray nativeArray) throws ScriptException,  
  105.             NoSuchMethodException {  
  106.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  107.         engine.put("list", list);  
  108.         engine.put("arr", nativeArray);  
  109.         String script = "   function dosomething(){                                     "  
  110.                 + "                                                                             "  
  111.                 + "                     for (n=0; n< arr.length; n++){                           "  
  112.                 + "                         var map=new Packages.java.util.HashMap();           "  
  113.                 + "                         for (i in arr[n]){                                  "  
  114.                 + "                             map.put(i,arr[n][i]);                           "  
  115.                 + "                         }                                                   " + "                           list.add(map);                                      "  
  116.                 + "                     }                                                       " + "                   }                                                           ";  
  117.         engine.eval(script);  
  118.   
  119.         Invocable inv = (Invocable) engine;  
  120.         inv.invokeFunction("dosomething");  
  121.         for (Map<String, Object> map : list) {  
  122.             Set<Entry<String, Object>> entrySet = map.entrySet();  
  123.             for (Entry<String, Object> entry : entrySet) {  
  124.                 Object object = entry.getValue();  
  125.                 if (object instanceof NativeArray) {  
  126.   
  127.                     map.put(entry.getKey(), array2list(engine,  
  128.                             (NativeArray) object));  
  129.                 } else if (object instanceof NativeObject) {  
  130.                     map.put(entry.getKey(), obj2map(engine,  
  131.                             (NativeObject) object));  
  132.                 }  
  133.             }  
  134.   
  135.         }  
  136.   
  137.         return list;  
  138.   
  139.     }  
  140.   
  141.     public static Map<String, Object> obj2map(ScriptEngine engine,  
  142.             Object nativeObject) throws ScriptException, NoSuchMethodException {  
  143.         Map<String, Object> map = new HashMap<String, Object>();  
  144.   
  145.         engine.put("map", map);  
  146.         engine.put("obj", nativeObject);  
  147.         String script = "   function dosomething(){                                         "  
  148.                 + "                         for (i in obj){                                         "  
  149.                 + "                             map.put(i,obj[i]);                                  "  
  150.                 + "                         }                                                       " + "                   }                                                               ";  
  151.         engine.eval(script);  
  152.   
  153.         Invocable inv = (Invocable) engine;  
  154.         inv.invokeFunction("dosomething");  
  155.         return map;  
  156.   
  157.     }  
  158.   
  159. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多