1. 引擎工厂的属性

引擎

名字

MIME类型

文件扩展

Nashorn

nashorn,Nashorn

js,JS

JavaScript,javascript

ECMAScript,mcmascript

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

2. 获取manager


ScriptEngineManager manager = new ScriptEngineManager();
System.out.println("Available factories: ");

3.  查看线程安全

for (ScriptEngineFactory factory : manager.getEngineFactories()){
    System.out.println(factory.getEngineName());
    
    //null:不安全
    //MULTITHREADED:安全
    //...
    System.out.println("线程安全:"+factory.getParameter("THREADING"));
}

4. 获取js引擎


final ScriptEngine engine = manager.getEngineByName("nashorn");
if (engine == null) {
System.err.println("No engine for nashorn");
System.exit(1);
}

5. 调用脚本

engine.eval("n=88");
Object evalResult = engine.eval("n+2");
System.out.println(evalResult);

engine.put("x", 99);
evalResult = engine.eval("x+2");
System.out.println(evalResult);

6. 重定向输出

Writer orinalWriter = engine.getContext().getWriter();
engine.getContext().setWriter(new PrintWriter("E:\\js.txt"));
engine.eval("print('hello')");
engine.getContext().setWriter(orinalWriter);

//只有脚本引擎的输出被改变
System.out.println("hello");

7. 调用函数

engine.eval("function greet(how ,whom) {return how+','+whom}");
evalResult = ((Invocable)engine).invokeFunction("greet", "hello","world");
System.out.println(evalResult);

8. 调用方法

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')");
evalResult = ((Invocable)engine).invokeMethod(yo, "welcome","world");
System.out.println(evalResult);

9.调用接口

package shell;

public interface Greeter {
String welcome(String whom);
}
//定义function
engine.eval("function welcome(whom) {return 'welcome hello,'+whom}");

Greeter greeter = ((Invocable)engine).getInterface(Greeter.class);
evalResult = greeter.welcome("world");
System.out.println(evalResult);

10. 编译脚本

if(engine instanceof Compilable){
CompiledScript compiledScript = ((Compilable)engine).compile("print('hello xxx')");
compiledScript.eval();
}