Call Methods in Sequence

纵饮孤独 提交于 2019-12-12 04:09:17

问题


I have 5 different methods like this

public void met1(){}
public void met2(){}
public void met3(){}
public void met4(){}
public void met5(){}

I want to call this method from 1 to 5 is there any convinient way to do this.

I don't want to call one by one or I don't want to put method call inside other method.

How Can I do this??


回答1:


Have you looked into fluent design patterns? http://www.javacodegeeks.com/2013/01/fluent-object-creation.html

Example would be something like this:

myObject.met1().met2().met3().met4().met5().result();



回答2:


I believe you could do it with reflection with something like:

YourClass classInstance = new YourClass();

for (int i = 1; i < 6; i++) {
    Method yourMethod = YourClass.class.getMethod("met" + i);

    method.invoke(instance);
} 

Haven't tested it out, so no guarantees.




回答3:


You could do this with reflection as other answers have previously mentioned. Reflection is generally avoided if possible.

In reality the most common design pattern to address your concern would be Chain of Responsibility.
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern




回答4:


The only way to call methods by name is through reflection. See this article for how to do this:

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

Something like this should work:

 for (int i = 1; i < 6; i++){
      java.lang.reflect.Method method; 
      try {
           method = this.getClass().getMethod("met" + i);
           method.invoke(this);
      } catch (SecurityException e) {
           // ...
      } catch (NoSuchMethodException e) {
           // ...
      }
 }


来源:https://stackoverflow.com/questions/22514947/call-methods-in-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!