码迷,mamicode.com
首页 > 编程语言 > 详细

用ScriptEngine在java中和javascript交互的例子(JDK6新特性)

时间:2014-08-15 17:19:59      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   java   io   for   ar   art   

1. [代码][Java]代码     
package demo7;
 
import java.util.Arrays;
import java.util.List;
 
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
 
public class ScriptEngineTest {
 
    public static void main(String[] args) throws Exception {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");
 
        // 1
        engine.put("msg", "just a test");
        String str = "msg += ‘!!!‘;var user = {name:‘tom‘,age:23,hobbies:[‘football‘,‘basketball‘]}; var name = user.name; var hb = user.hobbies[1];";
        engine.eval(str);
 
        String msg = (String) engine.get("msg");
        String name = (String) engine.get("name");
        String hb = (String) engine.get("hb");
        System.out.println(msg);
        System.out.println(name + ":" + hb);
 
        // 2
        engine.eval("function add (a, b) {c = a + b; return c; }");
        Invocable jsInvoke = (Invocable) engine;
 
        Object result1 = jsInvoke.invokeFunction("add", new Object[] { 10, 5 });
        System.out.println(result1);
 
        // 3
        Adder adder = jsInvoke.getInterface(Adder.class);
        int result2 = adder.add(10, 35);
        System.out.println(result2);
 
        // 4
        engine.eval("function run() {print(‘www.java2s.com‘);}");
        Invocable invokeEngine = (Invocable) engine;
        Runnable runner = invokeEngine.getInterface(Runnable.class);
        Thread t = new Thread(runner);
        t.start();
        t.join();
 
        // 5
        String jsCode = "importPackage(java.util);var list2 = Arrays.asList([‘A‘, ‘B‘, ‘C‘]); ";
        engine.eval(jsCode);http://www.bizhizu.cn/shouhui/?
        List<String> list2 = (List<String>) engine.get("list2");
        for (String val : list2) {手绘图片
            System.out.println(val);
        }
         
    }
}
 
interface Adder {
    int add(int a, int b);
}

用ScriptEngine在java中和javascript交互的例子(JDK6新特性),布布扣,bubuko.com

用ScriptEngine在java中和javascript交互的例子(JDK6新特性)

标签:style   http   color   java   io   for   ar   art   

原文地址:http://www.cnblogs.com/xkzy/p/3915074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!