I have an ManagerCLass, which includes many other Objects. Here are methodes, that takes thes Objects and call an method on theses Objects.. Example:
public class Manager extends BaseManager {
ClassA classA = new ClassA();
ClassB classB = new ClassB();
ClassC classC = new ClassC();
ClassD classD = new ClassD();
ClassE classE = new ClassE();
public void callMethodsOnObjects() {
classA.printResult();
classB.printResult();
classC.printResult();
classD.printResult();
classE.printResult();
}
}
These classes have all the same Superclass. Now my Question is, is there a way to automate the callMethodsOnObjects()-method?
My Idea was to get all declaredClasses of the Managerclass. Then to Loop of the array an excecute the printResult()-methode on each Object.
Class<?>[] classes = Manager.class.getDeclaredClasses();
for (int i = 0; i < classes.length; i++) {
....
}
But this don´t work. The Array is Empty.
So do you have an Idea if this a way to automate this? There are still more methods that are structured this way. I'm not getting anywhere here. Does it make sense to do it this way, as I imagined it?
OK, so the real problem here is that you are using Java terminology incorrectly.
There are no member classes of the
Managerclass. Yup. That's what I said!A "member class" is a class that is declared inside another class. But there aren't any classes declared inside
Manager.However, there are fields ("member fields") declared inside
Manager; i.e.classA,classBand so on. And these fields have classes; i.e.ClassA,ClassBand so on.If you want to find the member fields of a class, use the
Class.getDeclaredFields()method. This will give you an array ofFieldobjects.You can then get each field's class by calling
Field.getType()on it. Then you can use reflection to lookup the classsesprintResult()method and invoke it on the value in the respective fields of a target object.Notes:
The
Classreturned bygetType()could denote a primitive type or array type rather than a class. ThisClasswill represent the erased type of the field.If you want the
Typeas it was declared in the source code, useField.getGenericType()instead.