Finding field exist or not through reflection

java, reflection

Solution

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
      }
    }

Problem

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

Original source

Related problems