java中执行javascript案例
程序员文章站
2022-04-14 18:06:42
Nashorn js engine官方文档 https://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/#top java函数输出js的hello world: 调用文件里的js脚本: ......
nashorn js engine官方文档
java函数输出js的hello world:
import javax.script.invocable;
import javax.script.scriptengine;
import javax.script.scriptenginefactory;
import javax.script.scriptenginemanager;
import javax.script.scriptexception;
public class maub {
public static void main(string args[]) throws scriptexception, nosuchmethodexception{
//引擎管理器
scriptenginemanager m = new scriptenginemanager();
//获取引擎
scriptengine engine = m.getenginebyname("javascript");
//执行javascript代码
engine.eval("function hello(name){print('hello '+name)}");
//javascript实现了invocable调用接口
invocable inv = (invocable) engine;
//调用函数hello,传入world
inv.invokefunction("hello","world");
}
}
调用文件里的js脚本:
import java.io.filenotfoundexception;
import javax.script.invocable;
import javax.script.scriptengine;
import javax.script.scriptenginefactory;
import javax.script.scriptenginemanager;
import javax.script.scriptexception;
public class maub {
public static void main(string args[]) throws scriptexception, nosuchmethodexception, filenotfoundexception{//引擎管理器
scriptenginemanager m = new scriptenginemanager();
//获取引擎
scriptengine engine = m.getenginebyname("javascript");
//执行javascript代码
engine.eval(new java.io.filereader("e:\\code\\java\\src\\getpwd.js"));
invocable inv = (invocable) engine;
string arg[] = {"mdwwdqyjkozihvcnaqebbqadkwaw","fot123456"};
//使用invocable调用脚本函数,传入string参数
system.out.println(inv.invokefunction("getpwd",arg));
}
}
上一篇: redux源码学习笔记 - applyMiddleware
下一篇: js如何生成id随机数