I am using inherited bean classes for my project. Here some of super classes will be empty and sub class can have fields & some of sub classes will be empty and super class can have fields.
My requirement is to get all private / public fields from Sub class as well as to get all public / protected fields from Super class too.
Below I have tried to achieve it. But I failed to meet my requirement. Please provide some suggestion to achieve this one.
Field fields [] = obj.getClass().getSuperclass().getDeclaredFields();
If I use above code, I can get only Super class fields
Field fields [] = obj.getClass().getFields();
If I use above code, I can get all fields from Sub class and super class fields
Field fields [] = obj.getClass().getDeclaredFields();
If I use above code, I can get Sub class public and private all fields.
When a subclass defines a field with the same name, the subclass just declares a new field. The field in the superclass is hidden. It is NOT overridden, so it can not be accessed polymorphically.
The only way we have to get only inherited fields is to use the getDeclaredFields() method, as we just did, and filter its results using the Field::getModifiers method. This one returns an int representing the modifiers of the current field. Each possible modifier is assigned a power of two between 2^0 and 2^7.
No, a superclass has no knowledge of its subclasses.
Now how can i get fields of parent class in this case 'a'. You can use getField() with public fields. Otherwise, you need to loop through parent classes yourself.
You will have to iterate over all the superclasses of your class, like this:
private List<Field> getInheritedPrivateFields(Class<?> type) {
List<Field> result = new ArrayList<Field>();
Class<?> i = type;
while (i != null && i != Object.class) {
Collections.addAll(result, i.getDeclaredFields());
i = i.getSuperclass();
}
return result;
}
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