java如何读取js里面的方法呢?以下是java读取普通js方法实例
此方法对带有document、windows的js会报错,目前还没研究出来怎么弄,有知道的大哥大姐能评论告诉一下我么!!
1.创建读取类
public class ScriptJs {
public String userjs(String filename) throws ScriptException, NoSuchMethodException, IOException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
FileReader reader = new FileReader(filename); // 执行指定脚本
engine.eval(reader);
String ret ="";
if (engine instanceof Invocable) {
Invocable invoke = (Invocable) engine;
ret = (String) invoke.invokeFunction("encrypt","ABCD"); //方法名和参数
//System.out.println("s = " + s);
}
reader.close();
return ret;
}
}
2.js里面的代码
function encrypt(a){
return a+"EFG";
}
3.测试以下
public class Test {
public static void main(String[] args) throws ScriptException, IOException, NoSuchMethodException {
ScriptJs js = new ScriptJs();
String s = js.userjs("D:\\ideaProjects\\ThirdInterfaceTest\\src\\main\\java\\com\\example\\httpURLConnection\\sign.js");
//String s = js.userjs("src/main/java/com/example/httpURLConnection/sign.js"); 两种都可以
System.out.println("s = " + s);
}
}
4.结果: