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";
6
  • 2
    Why didn't reflection work? Commented Jan 20, 2013 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. Commented Jan 20, 2013 at 20:48
  • If you're calling the method identified by et, why bother looking it up in the array? Commented Jan 20, 2013 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. Commented Jan 20, 2013 at 20:50
  • 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... Commented Jan 20, 2013 at 21:01

2 Answers 2

2

You will have to use reflection. Something like this:

getClass().getMethod(arr[i]).invoke(this);
Sign up to request clarification or add additional context in comments.

1 Comment

--Working with this aswell. All the same.
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");
}

}

1 Comment

What do you consider a bad design? Using the Reflection api?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.