Calling a method by its name

Possible duplicate:
How to call a Java method when specifying the method name as a string?

I have 10 methods: m1

, m2

, m3

, ...

like this:

public void m1(){
..
}

      

How can I call them with a string in a 'for' loop?

I want to do this:

for (int i=1;i<11;i++){
   invoke('m'+i);
}

      

+2


source to share


3 answers


For this you need to use reflection

.

    Method method = getClass().getMethod(methodName);
    method.invoke(this);

      



So, you need to store the method names in an array and use that piece of code to call those methods one by one.

+4


source


You can do this with reflection .



However, I will be interested in your use case. You can often refactor your application so that the use of reflection is overkill.

0


source


Use java reflection on object this

.

-1


source







All Articles