import java.io.File;
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 Nashorn {
public static void main(String[] args) {
Nashorn nashorn = new Nashorn();
//使用Java8的函数式编程方式的
// :: 方法引用关键字
Converter<String, String> converter = nashorn::InvokeJsFunc;
String result = converter.convert("D://testfile/script.js");
System.out.println(result);
}
public String InvokeJsFunc(String fileName){
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
try {
scriptEngine.eval(new FileReader(new File(fileName)));
} catch (FileNotFoundException | ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//转换为 Invocable 接口来调用的JS函数的接口
Invocable invocable = (Invocable) scriptEngine;
Object result = null;
try {
//调用的JavaScript的方法
//第一个参数是函数名第二个函数形参
result =invocable.invokeFunction("fun1", "Jhon");
// System.out.println(result);
} catch (NoSuchMethodException | ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result.toString();
}
@FunctionalInterface
interface Converter<F,T>{
T convert(F from);
}
}
script.js
var fun1 = function(name)
{
print('Hi there from JavaScript '+name);
return "Greetings from JavaScript";
};