在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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/09f352357a505f6c3a0a5ebeb96bc3eb.html