import javax.script.*; import java.io.*; import java.util.*; import static java.lang.System.*; public class ListScriptEngines { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); // 得到所有的脚本引擎工厂 List<ScriptEngineFactory> factories = manager.getEngineFactories(); // 这是Java SE 5 和Java SE 6的新For语句语法 for (ScriptEngineFactory factory: factories) { // 打印脚本信息 out.printf("Name: %s%n" + "Version: %s%n" + "Language name: %s%n" + "Language version: %s%n" + "Extensions: %s%n" + "Mime types: %s%n" + "Names: %s%n", factory.getEngineName(), factory.getEngineVersion(), factory.getLanguageName(), factory.getLanguageVersion(), factory.getExtensions(), factory.getMimeTypes(), factory.getNames()); // 得到当前的脚本引擎 ScriptEngine engine = factory.getScriptEngine(); } } } |
Name: Mozilla Rhino Version: 1.6 release 2 Language name: ECMAScript Language version: 1.6 Extensions: [js] Mime types: [application/javascript, application/ecmascript, text/javascript, text/ecmascript] Names: [js, rhino, JavaScript, javascript, ECMAScript, ecmascript] |
ScriptEngine engine = manager.getEngineByExtension("js"); |
ScriptEngine engine = manager.getEngineByMimeType("text/javascript"); |
ScriptEngine engine = manager.getEngineByName("javascript"); |
import javax.script.*; import java.io.*; import static java.lang.System.*; public class FirstJavaScript { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); // 得到javascript脚本引擎 ScriptEngine engine = manager.getEngineByName("javascript"); try { // 开始运行脚本,并返回当前的小时 Double hour = (Double)engine.eval("var date = new Date();" +"date.getHours();"); String msg; // 将小时转换为问候信息 if (hour < 10) { msg = "上午好"; } else if (hour < 16) { msg = "下午好"; } else if (hour < 20) { msg = "晚上好"; } else { msg = "晚安"; } out.printf("小时 %s: %s%n", hour, msg); } catch (ScriptException e) { err.println(e); } } } |
上面的例子通过得到当前的小时,并将其转化为问候语。上面的程序的输出信息为:
小时9.0:上午好
这个例子最值得注意的是执行的2句脚本,最后一句是date.getHours()。并未将这个值赋给一个javascript变量。这时,eval方法就将这样的值返回。这有些类似C语言的(…)运算符。如(c=a+b, c + d),这个表达式的返回值是a+b+d。
[1] [2] [3] 下一页