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