How to Make a JavaScript Engine
Java Specification Request (JSR) 223 addresses the issues regarding the non-standardization of procedures or classifications of Java class files with other languages by defining a standard framework and application programming interface (API) that will assist developers in integrating Java technology with other scripting languages. This methodology provides ways for developers to access and control Java technology-based objects from a scripting environment, to create and design Web content with scripting languages and to embed scripting environments within Java technology-based elements.
Instructions
-
-
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.
-
1
Tips & Warnings
Take advantage of the various free online tutorials to learn the basics of Java programming.
Join discussion forums to become familiar with the Java programming lingo.
References
Resources
- Photo Credit Stockbyte/Stockbyte/Getty Images