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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.