Java虚拟机能支持JavaScript、Scala、JRuby、Jython和Groovy等脚本语言.
Java虚拟机支持脚本的意义在于实现函数式编程, 即脚本中最重要的便是方法.
根据引擎名称,文件后缀,MIME或取脚本引擎, 并执行输出语句.
代码语言:javascript复制@Test
public void hello() throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
//ScriptEngine engine = manager.getEngineByExtension("js");
//ScriptEngine engine = manager.getEngineByMimeType("text/javascript");
engine.eval("print('Hello World!');");
}
将参数传入脚本并执行
代码语言:javascript复制@Test
public void testBinding() throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
Bindings bindings = new SimpleBindings();
bindings.put("param", "playing games");
engine.eval("print('I like ' param);", bindings);
File file = new File("test.txt");
engine.put("files", file);
engine.eval("print(files.getAbsolutePath());print(files.getName());");
}
通过脚本上下文修改输出重定向到文件并执行脚本
代码语言:javascript复制@Test
public void scriptToFile() throws IOException, ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
context.setWriter(new FileWriter("output.txt"));
engine.eval("print('Hello World!');");
}
调用脚本中函数, 并传参执行. 一些脚本引擎允许使用者单独调用脚本中的某个方法, 支持此操作的脚本引擎可以通过实现javax.script.Invocable接口, JavaSE中的JavaScript引擎已实现了Invocable接口.
代码语言:javascript复制@Test
public void invokeFunction() throws ScriptException, NoSuchMethodException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String scriptText = "function greet(name) { print('Hello, ' name); } ";
engine.eval(scriptText);
Invocable invocable = (Invocable) engine;
invocable.invokeFunction("greet", "Alex");
}
在脚本语言中,调用JDK中类和方法.
Packages是脚本语言里的一个全局变量,专用于访问JDK的package.
Invocable 接口允许java平台调用脚本程序中的函数或方法.
代码语言:javascript复制@Test
public void testInvocable() throws ScriptException, NoSuchMethodException, InterruptedException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
String js = "function doSwing(t){var f=new Packages.javax.swing.JFrame(t);f.setSize(400,300);f.setVisible(true);}";
engine.eval(js);
Invocable inv = (Invocable) engine;
inv.invokeFunction("doSwing", "Scripting Swing");
Thread.currentThread().join();
}
对于在文件中的脚本也可以利用FileReader读入JDK并执行.
代码语言:javascript复制public static void testScript() {
try (FileReader fr = new FileReader("test.js")) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval(fr);
} catch (Exception ex) {
ex.printStackTrace();
}
}
除了JS文件可以解析外, 其他类别脚本也可以解析执行, 执行需要额外的jar做为支撑.
例如执行Python脚本, 需要额外jython-standalone.jar.
代码语言:javascript复制<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>