示例
定义一个SuperClass
的实体类,分别定义四种修饰符的字段(Field)
public class SuperClass {
public String superPublicField;
protected String superProtectedField;
String superDefaultField;
private String superPrivateField;
}
定义一个子类,继承于Person
public class SubClass extends SuperClass {
public String subPublicField;
protected String subProtectedField;
String subDefaultField;
private String subPrivateField;
}
测试
public class Main {
public static void main(String[] args) {
Class<SubClass> studentClass = SubClass.class;
System.out.println("getDeclaredFields:\n");
Field[] declaredFields = studentClass.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field.getName());
}
System.out.println("================分割线================");
System.out.println("getFields:\n");
Field[] fields = studentClass.getFields();
for (Field field : fields) {
System.out.println(field.getName());
}
}
}
从打印结果可以看出,getDeclaredFields
只会获取本类的字段,而getFields
只会获取本类和父类中公有的字段