程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> ScriptEngine在java中和javascript交互的例子(JDK6新特性)

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

編輯:關於JSP

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

上代碼:

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);
List<String> list2 = (List<String>) engine.get("list2");
for (String val : list2) {
System.out.println(val);
}

}
}

interface Adder {
int add(int a, int b);
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved