4

我不确定在复合组件中处理方法表达式的“正确”方式。

我的复合材料使用带有操作方法的支持类。这些执行一些默认操作或委托给复合用户作为属性传递的操作方法:

在使用页面中:

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

合成的:

<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>

支持类:

@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;

}

}

上面的代码按预期工作,但我发现它相当庞大,它创建了一个 ValueExpression 来从声明的“action”属性中检索方法表达式。

UIComponentBase 提供getValueExpression("attributeName")但 MethodExpressions 没有类似的东西。

所以我的问题是,是否有MethodExpressions比上面的代码更好的方法来评估复合组件中声明为属性的方法。

谢谢

4

1 回答 1

4

Get it as attribute instead of as value expression.

So, instead of

ValueExpression ve = getValueExpression("action");

do

MethodExpression me = (MethodExpression) getAttribute("action");
于 2011-12-16T11:15:43.270 回答