mardi 9 novembre 2021

Reflection - trying to get a reference for class field to pass it as an argument

I'm trying to print public properties of an object which can be primitives or also an object by using Reflection I manage to print the methods and primitive fields but when I try to send recursively the field of type class I get an error(in line printProperties(o);).

example - public class A { public Class B }

How can I send a references of class B to printProperties ?

        Class reflectClass = (Class) reflectObject;
         String className = reflectClass.getName();
         System.out.println(className);
         Method [] classMethod = reflectClass.getMethods();
         for(Method m :classMethod){
             System.out.println("Name "+m.getName());
             System.out.println("Return "+m.getReturnType());
         }
         System.out.println("Fields");
         Field[] fields = reflectClass.getDeclaredFields();
         for (Field f : fields){
             if(f.getType().isPrimitive()||f.getType().isAssignableFrom(String.class)){
                 System.out.println("Field "+f.getName());
             }
             else {
                 Object o = f.get(this);
                 printProperties(o);
            }```






Aucun commentaire:

Enregistrer un commentaire