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