1

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";
Community
  • 1
  • 1
JEV
  • 2,494
  • 4
  • 33
  • 47
  • 2
    Why didn't reflection work? – dutt Jan 20 '13 at 20:47
  • What did you try with reflection? It would be helpful to actually tell us what you tired rather than just stating it doesn't work when clearly reflection would work. – Jon Taylor Jan 20 '13 at 20:48
  • If you're calling the method identified by `et`, why bother looking it up in the array? – Sergey Kalinichenko Jan 20 '13 at 20:49
  • The accepted answer in the first comment would work. In your case, you can change where they use "obj" to "this" since your methods are in the current class. – Erik Nedwidek Jan 20 '13 at 20:50
  • I also tried the methodposted by Makoto. It asks to surround it with try catch, which i did, and it failed. I will post my code, I will edit main post – JEV Jan 20 '13 at 20:56
  • 1
    you can not call the method-object if it is null. it does not return any value, so do not cast and return the result. put your getMethod and the invoke in one try block instead... – Martin Seeler Jan 20 '13 at 21:01

2 Answers2

2

You will have to use reflection. Something like this:

getClass().getMethod(arr[i]).invoke(this);
partlov
  • 13,789
  • 6
  • 63
  • 82
2

You can use the ReflectionAPI to achieve this. Just get the method with this name from your desired class (if available ) and invoke it with your args, in this case null.

BUT it's a bad design and you should rethink your application flow!

here is an example:

public class HelloWorld {

public static void main(String[] args) {
    HelloWorld hello = new HelloWorld();
    String[] calls = { "def", "abc", "ghi" };
    try {
        for (String call : calls) {
            Method method = HelloWorld.class.getMethod(call, null);
            method.invoke(hello, null);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}

public void abc() {
    System.out.println("abc");
}

public void def() {
    System.out.println("def");
}

public void ghi() {
    System.out.println("ghi");
}

}

Martin Seeler
  • 6,874
  • 3
  • 33
  • 45