In Java 6, scripting engine support is built in. For example,
// Create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// Create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// Evaluate JavaScript code from String
engine.eval("print('Hello, World')");
Why would you use one? Some reasons:
- you have a library in a scripting language that you want to use in Java (e.g. a Python library that you could run via Jython)
- You want to provide a configurable programming mechanism for customers, such that they can provide short code snippets. For example, I've done this in the past allowing customers to write filters using JavaScript (e.g. is x < 2 and y > 5 and z > 10 ?).
- You can implement more complex logic in tools like Ant by scripting directly in the configuration file
- You can implement solutions in a language more suited to that domain (e.g. using lambdas via Clojure), but maintain your reliance on the JVM.
Implementations include Rhino (a Java implementation of Javascript), Jython (a Java Python) and many more.