4

i have a submit button. This submit button has an "action" attribute. But this action attribute should always call another function (some kind of generic). So i want to call a function dynamically. This is because i need to reuse this component. I just don't know which Type the action attribute needs (Method, String, etc. ?) and how to refer correctly to the wanted "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
   }

}

In EL:

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

This seems tricky.. I hope somebody can help me. Do i need Reflection ? or an EL Resolver or anything else ??

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
sofarsoghood
  • 243
  • 2
  • 16

1 Answers1

8

Use the brace notation #{bean[foo]} to evaluate "dynamic" method and property names.

Your specific case can be solved as below:

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

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thx a lot Balus ! So when i have a Bean MethodBean and in there the method cancel() i would call it with #{methodBean[methodBean.cancel]} ? – sofarsoghood Oct 21 '15 at 06:45
  • If `#{methodBean.cancel}` returns a `String` representing the method name, yes. – BalusC Oct 21 '15 at 07:33