动态调用 EL 中的方法,该方法是从 String 求值的

Dynamically call method in EL, which is evaluated from a String

我有一个提交按钮。这个提交按钮有一个 "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]}">

另请参阅:

  • Dynamic ui include and commandButton