Java6 脚本引擎(用Java调用JS脚本)调用js
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JavaScriptEngineTest {
public static void main(String[] args) {
try {
JavaScriptEngineTest test = new JavaScriptEngineTest();
test.testAdd(5, 6);
} catch (Exception se) {
se.printStackTrace();
}
}
public String getPath() {
return this.getClass().getResource("/").getPath();
}
public void testAdd(int a, int b) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine jsEngine = sem.getEngineByName("js");
try {
jsEngine.eval(new FileReader(getPath() + "JavaScriptEngineTest.js"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ScriptException e) {
e.printStackTrace();
}
Invocable invocableEngine = (Invocable) jsEngine;
try {
Object ret = invocableEngine.invokeFunction("add", a, b);
System.out.println(ret);
} catch (ScriptException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
JavaScriptEngineTest.js,放在同一目录:
function add(a,b) {
return a+b;
}
输出:
11.0