Java8 Nashorn JavaScript引擎
Nashorn JavaScript引擎
Java 8提供了新的Nashorn JavaScript引擎,使得我们可以在JVM上开发和运行JS应用。Nashorn JavaScript引擎是javax.script.ScriptEngine的另一个实现版本,这类Script引擎遵循相同的规则,允许Java和JavaScript交互使用,例子代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package com.ehking.example.java8.newfeature.demo07;
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException;
public class Java8JavaScript {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); System.out.println(engine.getClass().getName());
try { System.out.println("output: " + engine.eval("function show() {return 10;}; show();")); } catch (ScriptException e) { e.printStackTrace(); }
}
}
|