We use cookies to collect and analyze information on site performance and usage,
to provide social media features and to enhance and customize content and advertisements.
import java.util.List;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
public class Scripting {
public static void main(String[] args) {
try {
// dump available engines
ScriptEngineManager mgr = new ScriptEngineManager();
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
for (ScriptEngineFactory engine : engines ) {
System.out.println(engine.getEngineName());
for ( String n: engine.getNames()) {
System.out.println("Short name : " + n);
}
}
/*
output :
Mozilla Rhino
Short name : js
Short name : rhino
Short name : JavaScript
Short name : javascript
Short name : ECMAScript
Short name : ecmascript
*/
// now execute a small script
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String myJSCode = "function myFunction() {"
+ " return (40 + 2);"
+ "}"
+"myFunction();";
System.out.println(engine.eval(myJSCode));
/*
output :
42
*/
}
catch (ScriptException ex) {
ex.printStackTrace();
}
}
}