0

我正在尝试ScriptEngine使用 name创建"nashorn"

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
if (engine == null) {
     System.out.println("engine == null");
} 

但我总是得到

engine == null

为什么会这样?文档说:

Nashorn 引擎是与 Java SE 开发工具包 (JDK) 捆绑在一起的默认 ECMAScript (JavaScript) 引擎。

这意味着 Nashorn 引擎是默认引擎,并且必须存在于 JDK 中,不是吗?

4

1 回答 1

4

这里有一个小片段列出所有支持的引擎

public class Script {
    public static void main(String[] args) throws ScriptException {
        new ScriptEngineManager().getEngineByName("js")
           .eval("print('Hello from Java\\n');");
        for (ScriptEngineFactory se : new ScriptEngineManager().getEngineFactories()) {
            System.out.println("se = " + se.getEngineName());
            System.out.println("se = " + se.getEngineVersion());
            System.out.println("se = " + se.getLanguageName());
            System.out.println("se = " + se.getLanguageVersion());
            System.out.println("se = " + se.getNames());
        }
    }
}

Java 6 (1.6.0_43)

Hello from Java
se = Mozilla Rhino
se = 1.6 release 2
se = ECMAScript
se = 1.6
se = [js, rhino, JavaScript, javascript, ECMAScript, ecmascript]

Java 7 (1.7.0_40)

Hello from Java                                                  
se = Mozilla Rhino                                               
se = 1.7 release 3 PRERELEASE                                    
se = ECMAScript                                                  
se = 1.8                                                         
se = [js, rhino, JavaScript, javascript, ECMAScript, ecmascript] 

Java 8 (1.8.0_74)

Hello from Java

se = Oracle Nashorn
se = 1.8.0_74
se = ECMAScript
se = ECMA - 262 Edition 5.1
se = [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript]
于 2016-05-18T12:54:13.760 回答