日期:2014-05-16  浏览次数:20408 次

在Java中使用ScriptEngine调用javascript

在jdk1.6之后版本中新增了ScriptEngine类,允许Java程序直接调用javascript代码
Java代码
package org.mystyle.js;
import java.io.File;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class InvokingJavaScript {
 public static void main(String[] args) throws Exception {
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("javascript");
  String fileName = "src/demo.js";
  File file = new File(fileName);
  FileReader reader = new FileReader(file.getAbsolutePath().replaceAll("\\\\", "/"));
  engine.eval(reader);
  if(engine instanceof Invocable){
   Invocable invoke = (Invocable) engine;
   Double sum = (Double) invoke.invokeFunction("addFun", 2, 3);
   System.out.println(sum);
  }
  reader.close();
 }
}

javascript文件demo.js
function addFun(a, b){
 return a+b;
}

 

输出:

5.0