In this post, I am going to explain how to get all the fields and inherited fields of a class.
Step 1: Get all the fields of current class using 'getDeclaredFields' method.
clazzTemp.getDeclaredFields()
Step 2: Get the super class of this class and repeat step 1 for this parent class. Do the steps 1 and 2 until the parent class is null.
clazzTemp.getSuperclass()
Example
public static List<Field> getAllFields(Class<?> clazz) {
List<Field> fields = new ArrayList<Field>();
Class<?> clazzTemp = clazz;
do {
fields.addAll(Arrays.asList(clazzTemp.getDeclaredFields()));
} while ((clazzTemp = clazzTemp.getSuperclass()) != null);
return fields;
}
Find the below working application.
AllFieldsOfAClass.java
package com.sample.app.fields;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AllFieldsOfAClass {
public static class Parent {
int parentA, parentB;
}
public static class Child extends Parent {
private int childA, childB;
}
public static List<Field> getAllFields(Class<?> clazz) {
List<Field> fields = new ArrayList<Field>();
Class<?> clazzTemp = clazz;
do {
fields.addAll(Arrays.asList(clazzTemp.getDeclaredFields()));
} while ((clazzTemp = clazzTemp.getSuperclass()) != null);
return fields;
}
public static void main(String args[]) {
getAllFields(Child.class).stream().forEach(field -> {
System.out.println(field.getName());
});
}
}
Output
childA childB parentA parent
Previous Next Home
No comments:
Post a Comment