使用Java语言编写的JavaScript的开源实现Rhino;
测试脚本引擎Rhino
public class Demo01{
//- 获得脚本引擎对象
public static void main(String[] args){
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");
//定义变量,存储到上下文中
engine.put("msg","hello");
String str = "var user = {name: "lpc" }";
str +="println(user.name");
engine.eval(str);//被js操作
engine.eval("msg = 'ssfaas'");
System.out.println(engine.get("msg"));//被java操作
//定义函数
engine.eval("function add(a,b){var sum = a+b;return sum;}");
//执行函数
Invocable jsInvoke = (Invocable)engine;
Object result = jsInvoke.invokefunction("add", new Objec[] {13,20})
//导入其他java包,使用其他包中的java类
String jsCode = "importPackage(java.util); var list = Arrays.asList([\"nihao\"])"
engine.eval(jsCode);
List<String> list2 = (List<String>) engine..get("list");
//执行一个js文件
URL url = Demo01.class.getClassLoader().getResource("a.js");
engine.eval(new FileReader(url.getPath()));
}
}
网友评论