9.3. Invoking Methods in an Expression

Problem

You are trying to print out a message that contains data returned by a method.

Solution

Commons JEXL can evaluate any method that is made available to the interpreter. The following expression invokes the language() method on an Opera bean. The acts property of Opera is a List, and this expression invokes the size( ) method on this List to obtain the number of acts in the Opera:

${opera.name} was composed by ${opera.composer} in ${opera.year}.
This opera has ${opera.acts.size( )}, and it is performed in ${opera.
language( )}

The following code creates and populates an expression and a context, merging the two to create a message:

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);
opera.acts( new ArrayList(2) );

String expr = 
    "${opera.name} was composed by ${opera.composer} in ${opera.year}.";
    "This opera has ${opera.acts.size( )} acts, and it is performed in " +
    "${opera.language( )}";

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

System.out.println( message );

The following message is printed to the console:

The Magic Flute was composed by Mozart in 1791. This opera has ...

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.