Java Scripting API有许多类和接口。它们在javax.script包中。
ScriptEngine
接口是其实例执行以脚本语言编写的脚本的接口
ScriptEngineFactory执行两个任务:
AbstractScriptEngine类是一个抽象类,并为ScriptEngine接口提供了部分实现。
ScriptEngineManager类发现和实例化脚本引擎。
以下代码显示如何列出所有可用的脚本引擎。
import java.util.List; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); // Get the list of all available engines List<ScriptEngineFactory> list = manager.getEngineFactories(); // Print the details of each engine for (ScriptEngineFactory f : list) { System.out.println("Engine Name:" + f.getEngineName()); System.out.println("Engine Version:" + f.getEngineVersion()); System.out.println("Language Name:" + f.getLanguageName()); System.out.println("Language Version:" + f.getLanguageVersion()); System.out.println("Engine Short Names:" + f.getNames()); System.out.println("Mime Types:" + f.getMimeTypes()); System.out.println("==="); } } }
上面的代码生成以下结果。
以下代码显示了如何使用JavaScript,Groovy,Jython和JRuby在标准输出上打印消息。
如果脚本引擎不可用,程序会向用户提示错误消息。
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) { // Get the script engine manager ScriptEngineManager manager = new ScriptEngineManager(); // Try executing scripts in Nashorn, Groovy, Jython, and JRuby execute(manager, "JavaScript", "print("Hello JavaScript")"); execute(manager, "Groovy", "println("Hello Groovy")"); execute(manager, "jython", "print "Hello Jython""); execute(manager, "jruby", "puts("Hello JRuby")"); } public static void execute(ScriptEngineManager manager, String engineName, String script) { ScriptEngine engine = manager.getEngineByName(engineName); if (engine == null) { System.out.println(engineName + " is not available."); return; } try { engine.eval(script); } catch (ScriptException e) { e.printStackTrace(); } } }
上面的代码生成以下结果。
要获得用于在标准输出上打印消息的语法,请使用ScriptEngineFactory类中的方法getOutputStatement(String toDisplay)。
以下代码段显示了如何获取Nashorn的语法。
import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) { // Get the script engine factory for Nashorn ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); ScriptEngineFactory factory = engine.getFactory(); // Get the script String script = factory.getOutputStatement("\"Vue5教程\""); System.out.println("Syntax: " + script); // Evaluate the script try { engine.eval(script); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
上面的代码生成以下结果。