动态调用EL中的方法,该方法从字符串求值



我有一个提交按钮。这个提交按钮有一个"action"属性。但是这个action属性应该总是调用另一个函数(某种泛型)。所以我想动态地调用一个函数。这是因为我需要重用这个组件。我只是不知道动作属性需要哪种类型(方法,字符串等?)以及如何正确引用想要的"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解析器或其他什么?

使用大括号符号#{bean[foo]}来计算"dynamic"方法和属性名。

您的具体情况可以按以下方式解决:

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

参见:

  • 动态ui包含和命令按钮

最新更新