November 2004
Intermediate to advanced
400 pages
10h 31m
English
You are trying to print out a message that contains data returned by a method.
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 ...
Read now
Unlock full access