package com.zdc.rhion;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class TestRhino {
public static void main(String[] args) {
//获得脚本引擎对象
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
//书写js变量
engine.put("msg", "hello js");
String str = "var obj = {name:'zs',arr:['asd','fgh']};";
str += "print(obj.name);";//打印输出使用print
try {
//执行脚本
engine.eval(str);
System.out.println(engine.get("msg"));
engine.eval("msg = \"sahjdfhs\"");
System.out.println(engine.get("msg"));
//定义函数
engine.eval("function test(){var a= 3;b=4;return (a+b)}");
//执行函数
Invocable invocable = (Invocable)engine;
Object object = invocable.invokeFunction("test", null);
System.out.println(object);
engine.eval("function test2(a,b){return eval(a+b)}");
Invocable invocable2 = (Invocable)engine;
Object object2 = invocable2.invokeFunction("test2", new Object[]{5,5});
System.out.println(object2);
//执行一个js文件
URL url = TestRhino.class.getClassLoader().getResource("ceshi.js");
FileReader reader = new FileReader(url.getPath());
engine.eval(reader);
reader.close();
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}