Thursday, September 9, 2010

Evaluating expressions with JEXL

JEXL is a useful library for implementing scripting features in Java programs - specifically it is useful if you require scripts to be evaluated like boolean expressions.

The first thing is to set up a JEXL engine,

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;

.....

JexlEngine jexl = new JexlEngine();

Then you initialize an jexl context

JexlContext context = new MapContext();

After that you add variables to your jexl context which can be used within your expressions.

e.g.

Integer x = new Integer(11);
context.set("x", x);

Now your jexl expressions can refer to x - e.g.
String expr = "x > 12"
Expression e = jexl.createExpression( expr );

Finally you can evaluate your expression, casting the result to the approproriate type:

Boolean result = (Boolean)e.evaluate(context);

You can see how this would be useful for any sort of user inputted expressions, etc.