Java Scripting API有許多類和接口。它們在javax.script包中。
ScriptEngine
接口是其實例執(zhí)行以腳本語言編寫的腳本的接口
ScriptEngineFactory執(zhí)行兩個任務(wù):
AbstractScriptEngine類是一個抽象類,并為ScriptEngine接口提供了部分實現(xiàn)。
ScriptEngineManager類發(fā)現(xiàn)和實例化腳本引擎。
以下代碼顯示如何列出所有可用的腳本引擎。
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("==="); } } }
上面的代碼生成以下結(jié)果。
以下代碼顯示了如何使用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(); } } }
上面的代碼生成以下結(jié)果。
要獲得用于在標準輸出上打印消息的語法,請使用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("\"w3cschool\""); System.out.println("Syntax: " + script); // Evaluate the script try { engine.eval(script); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
上面的代碼生成以下結(jié)果。
更多建議: