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
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With