在EL中动态调用方法,从String中计算

时间:2015-10-20 14:39:53

标签: jsf dynamic el commandbutton methodexpression

我有一个提交按钮。此提交按钮有一个"动作"属性。但是这个action属性应该总是调用另一个函数(某种泛型)。所以我想动态调用一个函数。这是因为我需要重用这个组件。我只是不知道action属性需要哪种类型(Method,String等?)以及如何正确引用所需的" BeanWithMethodToCall"。

@Named
@SessionScoped
public class BeanWithMethodToCall{

   @Inject
   private BeanWhichIsCalledFromEL elBean;

   public void methodToCall(){
      //do something
   }

   public void someLogic(){
      // here the wanted method is set on the bean which is later on called from el
      elBean.setMethodToCall("methodToCall");
   }
}

@Named
@SessionScoped
public class BeanWhichIsCalledFromEL{

   // i don't know the correct type of this :S
   private String method;

   public void setMethodToCall(String method){
      this.method = method;
   }

   // i don't know the correct return type of this :S
   public String getMethodToExecute(){
      //this method is called in the action attribute in the xhtml 
      // and should return a dynamic function to call
   }

}

在EL:

<h:commandButton value="Cancel" action="#{beanWhichIsCalledFromEL.getMethodToExecute()}">
    <f:ajax render="@form"/>
</h:commandButton>

这看起来很棘手......我希望有人可以帮助我。我需要反思吗?或EL解析器或其他任何东西??

1 个答案:

答案 0 :(得分:7)

使用大括号#{bean[foo]}来评估“动态”方法和属性名称。

您的具体案例可以解决如下:

<h:commandButton ... action="#{bean[bean.methodToExecute]}">

另见: