Monday, November 22, 2010

Executing EL expression for a method from a backing bean

In ADF we use expression language(EL) a lot when developing declaratively. At times though, we need to override or more likely, enhance the default functionality, by wrapping the the out of the box functionality with some extra code. A common case is when you have a button or action that is bound to an operation, on the data control though EL, and you want to invoke a backing bean before executing the binding. Inside the backing bean method,  after doing whatever that needed to be done, to invoke the actual server side functionality you can use the same EL that was bound by creating a method expression and invoking it. So to invoke any operation on the DataControl, like Commit, or Create or CreateInsert, from a backing bean using EL, you can create a helper method like this :
public Object invokeMethodExpression(String expr, Class returnType,
                                       Class[] argTypes, Object[] args)
  {
    FacesContext fc = FacesContext.getCurrentInstance();
    ELContext elctx = fc.getELContext();
    ExpressionFactory elFactory =
      fc.getApplication().getExpressionFactory();
    MethodExpression methodExpr =
      elFactory.createMethodExpression(elctx, expr, returnType, argTypes);
    return methodExpr.invoke(elctx, args);
  }

and invoke it like this :
String expr = "#{bindings.CreateInsert.execute}";
    invokeMethodExpression(expr, null, new Class[]{}, null);


The method uses the createMethodExpression method from ExpressionFactory. Read the javadoc to see how to pass arguments to the method.
This way, you can easily wrap the built in operations on a data control with your own custom code.

10 comments: