9.2. Using an Expression Language

Problem

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

Solution

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");
opera.setComposer("Mozart");
opera.setYear(1791);

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

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.

Discussion

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.