2

Possible Duplicate:
How do I invoke a Java method when given the method name as a string?

I have 10 methods named: m1, m2, m3,...

like this:

public void m1(){
..
}

How do I invoke them with string in a 'for' loop?

I want to do this:

for (int i=1;i<11;i++){
   invoke('m'+i);
}
Community
  • 1
  • 1
Wops
  • 983
  • 9
  • 23
  • 1
    You need to use a feature called "Reflection" – Karthik T Jan 24 '13 at 08:18
  • This isn't really a duplicate. The simple answer is use reflection but a design like this is wrong. You should, until Java gets first-class methods in the form of closures being using an interface to define the method signature and iterating over objects that implement that interface calling the method it defines. – Nick Holt Jan 24 '13 at 08:30

3 Answers3

4

You need to use reflection to achieve this.

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

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

Swapnil
  • 8,201
  • 4
  • 38
  • 57
  • ill just add and say that if u wish to add a parameter, add his Class in the getmethod() as 2nd parameter, and add the parameter in the invoke() as the 2nd parameter. – Wops Jan 24 '13 at 09:57
0

You can do this with reflection.

However, I would be interested in your use case. Often it is possible to refactor an application, so that the use of reflection is superfluous.

flash
  • 6,730
  • 7
  • 46
  • 70
-1

Use java reflection on this object.

GeorgeVremescu
  • 1,253
  • 7
  • 12
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – P.J Jan 24 '13 at 08:46
  • Was it not the purpose to offer some guidelines, hints and not specific answers? I mean, teach a man how to fish, but not give him the already caught fish... – GeorgeVremescu Jan 24 '13 at 09:24
  • your answer seems to be comment and not a real answer. If you want to give good answer write good description and proper formated answer.. – P.J Jan 24 '13 at 09:30