Java 平台的脚本

Wu Jun 2020-01-02 05:43:49
Categories: > > Tags:

1 获取脚本引擎

常用引擎

引擎 名字 MIME 类型 文件扩展
Nashorn nashorn,Nashorn,js,JS,JavaScript,javascript,ECMAScript,ecmascript application/javascript,application/ecmascript,text/javascript,text/ecmascript, js
Groovy groovy - groovy
Renjin Renjin text/x-R R, r, S, s
SISC Scheme sisc - scheme, sisc

可通过名字,MIME 类型或文件扩展来请求脚本引擎

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");

还可引入 jar 包支持更多引擎

2 脚本赋值与绑定

同一引擎上调用多个脚本,大多引擎都会保留之前定义的值

Object result = engine.eval(scriptString);
Object result = engine.eval(reader);

2.1 赋值

engine.put("k", 1728);
Object result = engine.eval("k + 1");

2.2 取值

engine.eval("n = 1728");
Object result = engine.get("n");

2.3 作用域

Bindings scope = engine.createBindings();
scope.put("b",new JButton());
engine.eval(scriptString, scope);

3 重定向输入和输出

可调用脚本上下文的 set 方法重定向脚本的标准输入输出

StringWriter writer = new StringWriter();
engine.getContext().setWriter(new PrintWriter(write, true));

Nashorn 引擎没有输入源的概念

4 调用脚本的函数和方法

4.1 面向过程

invokeFunction

//定义函数
engine.eval("function greet(how, whom){return how + ', ' + whom + '!'}");
//调用函数
result = ((Invocable)engine).invokeFunction("greet", "Hello", "World");

4.2 面向对象

invokeMethod

//定义对象
engine.eval("function Greeter(how){this.how = how}");
engine.eval("Greeter.prototype.welcome = function(whom){ return this.how + ', ' + whom + '!'}");
//调用方法
Object yo = engine.eval("new Greeter('Yo')");
result = ((Invocable)engine).invokeMethod(yo, "welcome", "World");

5 编译脚本

需要重复执行的时候,希望编译脚本

Reader reader = new FileReader("script.js");
CompiledScript script = null;
if(engine implements Compilable){
    script = ((Compilable)engine).compile(reader);
}
if(script != null){
    script.eval();
}sele{
    engine.eval(reader);
}