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
2 acts, and it is performed in German.

Discussion

This code is almost the same as the previous recipe, but you will notice that the expression contains a direct call to the opera.language( ) method and a call to the size( ) method on the acts property of opera.

Because JEXL is not governed by the Java Community Process (JCP), JEXL is free to extend the feature set of EL. Table 9-2 presents valid JEXL expressions that are actually invalid JSP 2.0 EL expressions.

Table 9-2. Extended capabilities of JEXL expression language

JEXL expression

Evaluates to

${object.function( )}

Accessing any function on an object, this evaluates to the return value from this function.

${"Wolfgang" + " " + "Mozart"}

JEXL supports string concatenation. This expression evaluates to “Wolfgang Mozart.”

${"Cow".size( )}

In JEXL you can get the size of a string like this. This expression evaluates to 3.

${hashMap.size( )}

On a map, JEXL will return the number of keys.

${arrayList.size( )}

Returns the size of a list.

See Also

For more information about Commons JEXL’s improvements on JSP 2.0 EL, see the Commons JEXL page (http://jakarta.apache.org/commons/jexl/).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.191.86