2

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!

.

2
  • 2
    Before you do this, consider whether the methods could be better named, and whether it would be simplest just to write one method that calls them all. Commented Sep 24, 2012 at 13:44
  • Would it not be better to add a method to your obj to call the method sequence? (I assume those are the real method names.) Commented Sep 24, 2012 at 13:48

3 Answers 3

3

Try something like:

   for (int i=0;i<N;i++) {
      try {
        obj.getClass().getMethod("method"+i).invoke(obj);
      } catch (Exception e) {
         // give up
         break;
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.