4

I am not sure about the "correct" way to deal with method expressions in composite components.

My composite uses a backing class with action methods. Theses perform some default actions or delegate to an action method passed by the composite user as an attribute:

In using page:

<my:component action="#{myBean.actionMethod}" />

Composite:

<cc:interface componentType="mycomponentType">
  <cc:attribute name="action" method-signature="java.lang.String action()" required="false" />
</cc:interface>

<cc:implementation>
  <h:commandButton value="submit" action="#{cc.componentAction}" />
</cc:implementation>

Backing class:

@FacesComponent("mycomponentType")
public class UIMyComponent extends UINamingContainer {   

public String action() {
    String outcome = "";

    ValueExpression ve = getValueExpression("action");
    String expression = ve.getExpressionString();

    FacesContext facesContext = FacesContext.getCurrentInstance();
    Application application = facesContext.getApplication();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory = application .getExpressionFactory();

    MethodExpression methodExpression = expressionFactory.createMethodExpression(elContext, expression, String.class, new Class[0]);

    outcome = (String) methodExpression.invoke(elContext, new Object[0]);

    if (outcome.equals("whatever")) {
        // set another outcome
    }


    return outcome;

}

}

The code above is working as expected, but I find it rather bulky and it creates a ValueExpression to retrieve the method-expression from the declared "action" attribute.

UIComponentBase offers getValueExpression("attributeName") but there is nothing similar for MethodExpressions.

So my Question is if there is a better way to evaluate MethodExpressions declared as attributes in composite components than the code above.

Thx

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Darkspirit
  • 199
  • 3
  • 12

1 Answers1

4

Get it as attribute instead of as value expression.

So, instead of

ValueExpression ve = getValueExpression("action");

do

MethodExpression me = (MethodExpression) getAttribute("action");
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thank you for your quick reply. I guess I'll stick to the bulky code since my component contains several command buttons and data tables, so inheritance from UICommand would be misleading. But a nice soultion for another problem class. – Darkspirit Dec 16 '11 at 12:48
  • In theory, you don't need to. There's only one `MethodExpression`, namely the currently invoked one, regardless of the amount of command buttons you have in the composite. – BalusC Dec 16 '11 at 12:51