调用js:
1 import java.io.FileNotFoundException;
2 import java.io.FileReader;
3 import javax.script.Invocable;
4 import javax.script.ScriptEngine;
5 import javax.script.ScriptEngineManager;
6 import javax.script.ScriptException;
7
8 public class JavaScriptEngineTest {
9 public static void main(String[] args) {
10 try {
11 JavaScriptEngineTest test = new JavaScriptEngineTest();
12 test.testAdd(5, 6);
13 } catch (Exception se) {
14 se.printStackTrace();
15 }
16 }
17
18 public String getPath() {
19 return this.getClass().getResource("/").getPath();
20 }
21
22
23 public void testAdd(int a, int b) {
24 ScriptEngineManager sem = new ScriptEngineManager();
25 ScriptEngine jsEngine = sem.getEngineByName("js");
26 try {
27 jsEngine.eval(new FileReader(getPath() + "JavaScriptEngineTest.js"));
28 } catch (FileNotFoundException e) {
29 e.printStackTrace();
30 } catch (ScriptException e) {
31 e.printStackTrace();
32 }
33 Invocable invocableEngine = (Invocable) jsEngine;
34 try {
35 Object ret = invocableEngine.invokeFunction("add", a, b);
36 System.out.println(ret);
37 } catch (ScriptException e) {
38 e.printStackTrace();
39 } catch (NoSuchMethodException e) {
40 e.printStackTrace();
41 }
42 }
43
44
45 }
JavaScriptEngineTest.js,放在同一目录:
1 function add(a,b) {
2 return a+b;
3 }
输出:
11.0
posted on 2006-12-26 14:11
交口称赞 阅读(972)
评论(0) 编辑 收藏 所属分类:
Java6