javaclassreflectionclass-members

Is there a way to get all Memberclasses of a class and loop over them to excecute methods?


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?


Solution

  • OK, so the real problem here is that you are using Java terminology incorrectly.

    There are no member classes of the Manager class. 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, classB and so on. And these fields have classes; i.e. ClassA, ClassB and so on.

    If you want to find the member fields of a class, use the Class.getDeclaredFields() method. This will give you an array of Field objects.

    You can then get each field's class by calling Field.getType() on it. Then you can use reflection to lookup the classses printResult() method and invoke it on the value in the respective fields of a target object.

    Notes:

    1. The Class returned by getType() could denote a primitive type or array type rather than a class. This Class will represent the erased type of the field.

    2. If you want the Type as it was declared in the source code, use Field.getGenericType() instead.