I am making university project.
I need to get all fields from class. Even private and inherited. I tried to get all declared fields and then cast to super class and repeat.
Fragment of my code:
private void listAllFields(Object obj) {
List<Field> fieldList = new ArrayList<Field>();
while (obj != null) {
fieldList.addAll(Arrays.asList(obj.getClass().getDeclaredFields()));
obj = obj.getClass().getSuperclass().cast(obj);
}
// rest of code
But it does not work. tmpObj
after casting is still the same class (not superclass).
I will appreciate any help how to fix casting problem, or how to retrieve these fields in different way.
Problem is not to gain access to fields, but to get names of fields!
I manages it that way:
private void listAllFields(Object obj) {
List<Field> fieldList = new ArrayList<Field>();
Class tmpClass = obj.getClass();
while (tmpClass != null) {
fieldList.addAll(Arrays.asList(tmpClass .getDeclaredFields()));
tmpClass = tmpClass .getSuperclass();
}
// rest of code
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…