Wednesday, July 22, 2009

Access Managed Bean Progmatically

Since
ValueBinding binding = application.createValueBinding and
context.getApplication().getVariableResolver().resolveVariable
are deprecated after jsf 1.2.

An uptodate approach is to utilize new lvalue feature of
Class ValueExpression
(http://java.sun.com/javaee/5/docs/api/javax/el/ValueExpression.html)

Example. (Jdeveloper 11 help center, 2 Getting Started with ADF Faces)

Example 2-15 Setting a New Object on a Managed Bean
public static void (String expression, Object newValue) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);

//Check that the input newValue can be cast to the property type
//expected by the managed bean.
//Rely on Auto-Unboxing if the managed Bean expects a primitive
Class bindClass = valueExp.getType(elContext);
if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
valueExp.setValue(elContext, newValue);
}
}

2 comments:

  1. To invoke method, use ExpressionFactory.createMethodExpression

    ReplyDelete
  2. FacesContext c=FacesContext.getCurrentInstance();
    Application app=c.getApplication();
    ExpressionFactory ef=app.getExpressionFactory();
    ELContext elc=c.getELContext();
    MethodExpression me=ef.createMethodExpression(elc,"#{mb.ivk}",null,new Class[]{});
    me.invoke(elc,null); //invoke void managedbean.ivk();

    ReplyDelete