前言:
1、jdk6的新特性中支持java代码执行JS文件。今天简单的学习了一下。
run.js 代码如下:
function sayHello() { print('hello world'); } function max(a,b) { return a > b ? a : b; }
?JAVA代码如下:
import javax.script.*; import java.io.*; public class RunScript { public static void main(String[] args) throws Exception{ String file = args[0]; FileReader scriptReader = new FileReader(new File(file)); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval(scriptReader); Invocable inv = (Invocable) engine; inv.invokeFunction("sayHello"); System.out.println(); System.out.println(inv.invokeFunction("max","100","100.2")); } }
?在控制台执行如下:
?执行成功。