Possible Duplicate:
How do I invoke a java method when given the method name as a string?
**I have looked at this : Call a function from a string array (Java or Groovy) and it didn't work for me, perhaps it is my scenario*
I have a String array with some values, and I want to be able to call a method which is one of those values, of course this can change, and I could potentially have 100's of values, so it's not feasible to use a if/else if construct, or a switch statement.
Is there any way I can call the method, as I would like, as displayed in the code below?
private String[] = {"Hit","Slap","Blop"}; private String et = "Slap"; public void Action(){ for(int i = 0; i < arr.length;i++){ if(et.equals(arr[i])){ //Call method of that name ( Slap(); ) } } } public void Run(){ /// } public void Slap(){ /// } public void Blop(){ /// } EDIT: My attempt to integrate reflection:
for(int i = 0; i < arr.length;i++){ if(et.equals(arr[i])){ //Call method of that name try { method = this.getClass().getMethod(arr[i]); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { return (String) method.invoke(this); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return "FAIL";
et, why bother looking it up in the array?