9.2. Using an Expression Language


You need to parameterize text messages with variables and bean properties.


Use Commons JEXL to evaluate an expression containing references to bean properties. To reference properties of an object, create an expression using the bean property syntax introduced in Chapter 3. Surround each property reference with curly braces and a leading $, as in the following example:

${opera.name} was composed by ${opera.composer} in ${opera.year}.

Use the following code to “merge” an instance of the Opera bean with the above expression:

import org.apache.commons.jexl.Expression;
import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;

Opera opera = new Opera( );
opera.setName("The Magic Flute");

String expr = 
    "${opera.name} was composed by ${opera.composer} in " +

Expression e = ExpressionFactory.createExpression( expr );
               JexlContext jc = JexlHelper.createContext( );
               jc.getVars( ).put("opera", opera);
               String message = (String) e.evaluate(jc);

System.out.println( message );

This code puts an instance of the Opera bean in a JexlContext and evaluates the expression, producing the following output:

The Magic Flute was composed by Mozart in 1791.


The previous example creates and populates an instance of the Opera bean: opera. An Expression object is then created by passing a String containing a JEXL ...

Get Jakarta Commons Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.