Java – Where is the Java scripting engine used?


How do I effectively use the "Scripting Engine" inside Java?

What are all the right use-cases to use the scripting engine?

Is there an open source project using "Scripting Engine"?

One thing comes to mind is "Closure, Functional programming" support is possible, but it is more of technical use than "Application Requirement".

Configurable plugins are OK. But still so many patterns (visitor, decorator) on high level can do the same.

I don't know the requirement well… how effectively it could be used in Java EE patterns… where it could complement with the existing patterns.

Moreover I would like to see more answers with some business usecases. Maybe like finding a complex discount for a product during sale based on membership or location. Finding ranking for a complex algorithm. Especially why not Java in some scenario? (or C# in .NET world)

Best Solution

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:

  1. 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)
  2. 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 ?).
  3. You can implement more complex logic in tools like Ant by scripting directly in the configuration file
  4. 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.