Bood Carley
Bood Carley

Reputation: 538

How to call multiple methods using loop in Java?

Supposes I have some methods like this:

method1()
method2()
method3()
method4()
method5()

But I don't want to call sequence methods:

obj.method1()
obj.method2()
obj.method3()
obj.method4()
obj.method5()

It's boring. And if I add a new method: method6(), I need add manual: obj.method6()

It's better if I can call them using a loop in Java. Anybody can give me some suggestions?

Thank!

.

Upvotes: 2

Views: 6483

Answers (3)

I do not know why you have used such naming convetion for your methods. If it was not only for example, you should consider to find better solution for them. Today it could be obvious for you but for followers of your code not really.

Regarding the manual addition of hypothetical method6. I think that adding one line of code is betther than reducing it and lossing the clarity of the code.

My suggestion is that, you should use the Facade pattern

Upvotes: 1

gnomie
gnomie

Reputation: 439

Try something like:

   for (int i=0;i<N;i++) {
      try {
        obj.getClass().getMethod("method"+i).invoke(obj);
      } catch (Exception e) {
         // give up
         break;
      }
    }

Upvotes: 3

Marko Topolnik
Marko Topolnik

Reputation: 200306

public static void callABunchOfMethods(Object obj, int count) throws Exception {
  for (int i = 1; i <= count; i++)
    obj.getClass().getMethod("method"+i).invoke(obj);
}

Upvotes: 2

Related Questions