我们要在Java中执行JavaScriptMethods.js中的execute(s1,s2)方法,JavaScriptMethods.js文件内容如下:
function execute(s1, s2){
return s1 + s2;
}
首先需要定义一个接口,这个接口中给出与要执行的JavaScript方法一样的方法签名,我们定义接口Methods,它的内容如下:
/**
* 接口中的方法签名必须与要执行的JavaScript方法一致
* @author yuncong
*
*/
public interface Methods {
public String execute(String s1,String s2);
}
然后,就可以用脚本引擎执行JavaScriptMethods.js中execute(s1,s2)方法了,具体内容写在下面的ExecuteScript类中的:
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class ExecuteScript {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
String path = ExecuteScript.class.getResource("").getPath();
System.out.println(path);
// FileReader的参数为所要执行的js文件的路径
engine.eval(new FileReader(path + "JavaScriptMethods.js"));
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
Methods executeMethod = invocable.getInterface(Methods.class);
System.out.println(executeMethod.execute("li", "yuncong"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行ExecuteScript类,输出如下:
/C:/Users/yuncong/git/login/target/classes/executescript/
liyuncong
时间: 2024-10-25 21:09:37