It can sometimes be useful to externalize some business logic from Java to a scripting environment which allows you to modify the logic at runtime. You can store the script in an external file or in database, and load it on each run. With little effort you can even add a code editor (e.g. using the excellent Editarea) to your application.
Java 6 SE comes with Rhino 1.6r2 bundled, so you don’t even need to add any jar to your project.
Let’s take a look at an example:
final Session session = HibernateUtil.getSession(); session.getTransaction().begin(); final Code code = (Code) session.get(Code.class, "1"); final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine jsEngine = manager.getEngineByName(code.getType()); final Employee employee = new Employee(); jsEngine.put("employee", employee); Integer result = (Integer) jsEngine.eval(code.getCode()); session.close();
I think this can be really useful and I will certainly use it in some of my projects in the near future.