Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding field exist or not through reflection

My class structure is as follows

   ClassA{}
   ClassB extends ClassA{}
   ClassC extends ClassB{}

these classes contains a field say name, I did not know in which class this field is present, i have a string name and object of ClassC. I am using reflection to get the field my code is

  private static Field getType(Object obj,String fieldName){

            Field type = null;
            try
            {
                    type = obj.getClass().getDeclaredField(fieldName);
            } 
            catch (NoSuchFieldException e) {
                    try
                    {
                            type = obj.getClass().getSuperclass().getDeclaredField(fieldName);
                    }
                    catch (NoSuchFieldException e1) {
                            e.printStackTrace();
                    }
            } catch (SecurityException e) {
                    e.printStackTrace();
            }
            return type;
    }

But it will check for field only in the current class and its super class, if i want to check the field till top level class, I need to keep write try catch blocks. i think it is not the correct way. Is there any alternate solution for this? Thanks in advance

like image 418
Siva Avatar asked Mar 30 '26 23:03

Siva


2 Answers

I think that you are trying to do something like:

   Class cls = obj.getClass();        
    for (Class acls = cls; acls != null; acls = acls.getSuperclass()) {
      try {
        Field field = acls.getDeclaredField(fieldName);
        // if not found exception thrown
        // else return field
        return field;
      } catch (NoSuchFieldException ex) {
        // ignore
      }
    }
like image 68
homik Avatar answered Apr 02 '26 12:04

homik


Use getField instead of getDeclaredField. It will look for the field in interfaces and parent classes recursively if it's not found immediately in the given class.

like image 23
Joni Avatar answered Apr 02 '26 14:04

Joni