- 1). Create a "ScriptEngineManager" object using the engine name. Here is the code for it:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval("print('Hello, world!')");
} catch (ScriptException ex) {
ex.printStackTrace();
}
You may also use API to search the list of supported scripting engines, but keep in mind that this process is slightly more complex than using the engine-name methodology. - 2). Use the following code to retrieve a ScriptEngine object from the script-engine manage. This method will search for all the scripting engines installed in your Java platform:
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> factories = mgr.getEngineFactories();
Once a script-engine factory is identified, the following details about the scripting language will be retrieved: the script-engine name and version, the language title and version, aliases for the script engine and a ScriptEngine object for the language used for scripting. Here is how it looks:
ScriptEngineFactory Info
Script Engine: Mozilla Rhino (1.6 release 2)
Engine Alias: js
Engine Alias: rhino
Engine Alias: JavaScript
Engine Alias: javascript
Engine Alias: ECMAScript
Engine Alias: ecmascript
Language: ECMAScript (1.6) - 3). Run the "ScriptEngine" object using the "eval" method to examine if the character sequence in your script is in order:
try {
jsEngine.eval("print('Hello, world!')");
} catch (ScriptException ex) {
ex.printStackTrace();
}
If no error is displayed, your JavaScript engine is compiled correctly and ready for use.
previous post
next post