"Iterating" through methods

user321068 picture user321068 · Jul 23, 2010 · Viewed 12.6k times · Source

Let's say I've got a Java object that's got among others the following methods:

public String getField1();
public String getField2();
public String getField3();
public String getField4();
public String getField5();

Is there a way to iterate through these methods and call 'em like the following code?

String fields = "";
for(int i = 1; i <= 5; i ++){
   fields += object.(getField+i) + " | ";
}

Thank you for your upcoming ideas.

Answer

Alberto Zaccagni picture Alberto Zaccagni · Jul 23, 2010
Class yourClass = YourClass.class;
for (Method method : yourClass.getMethods()){
    method.invoke(obj, args);           
}

See this guide for reference.