Reputation: 3753
I'm trying to create ScriptEngine
with name "nashorn"
:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
if (engine == null) {
System.out.println("engine == null");
}
But I always get
engine == null
Why is this happening? The docs say:
The Nashorn engine is the default ECMAScript (JavaScript) engine bundled with the Java SE Development Kit (JDK).
It means that the Nashorn engine is the default engine and must be present in JDK, don't it?
Upvotes: 1
Views: 3340
Reputation: 754
I had the same problem despite actually using Java 8.
To get it working, replace
ScriptEngineManager manager = new ScriptEngineManager();
With the following:
ScriptEngineManager manager = new ScriptEngineManager(null);
The reason the latter worked is mentioned in the following javadoc:
This constructor loads the implementations of ScriptEngineFactory visible to the given ClassLoader using the service provider mechanism.
If loader is null, the script engine factories that are bundled with the platform and that are in the usual extension directories (installed extensions) are loaded.
Upvotes: 0
Reputation: 22973
Here a small snippet to list all supported engines
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]
Upvotes: 4