Java 反射
操作属性(Attribute,或称“域”(Field))
getFields()
和 getDeclaredFields()
方法:前者只能得到公有的属性,后者得到类中的全部属性。
为了验证两个方法的效果,编写如下的示例代码:
先创建两个类:
class Base {
private static String basePrivateStaticField;
protected static String baseProtectedStaticField;
public static String basePublicStaticField;
private String basePrivateField;
protected String baseProtectedField;
public String basePublicField;
}
class Derived extends Base {
private static String derivedPrivateStaticField;
protected static String derivedProtectedStaticField;
public static String derivedPublicStaticField;
private String derivedPrivateField;
protected String derivedProtectedField;
public String derivedPublicField;
}
main
函数:
public static void main(String[] args) {
Class<Derived> derivedClass = Derived.class;
Field[] fields = derivedClass.getFields();
System.out.println("fields: ");
for (Field f : fields) {
System.out.println(" accessible: " + Modifier.toString(f.getModifiers()) + ", name: " + f.getName());
}
System.out.println();
Field[] declaredFields = derivedClass.getDeclaredFields();
System.out.println("declared fields: ");
for (Field f : declaredFields) {
System.out.println(" accessible: " + Modifier.toString(f.getModifiers()) + ", name: " + f.getName());
}
}
输出如下:
fields:
accessible: public static, name: derivedPublicStaticField
accessible: public, name: derivedPublicField
accessible: public static, name: basePublicStaticField
accessible: public, name: basePublicField
declared fields:
accessible: private static, name: derivedPrivateStaticField
accessible: protected static, name: derivedProtectedStaticField
accessible: public static, name: derivedPublicStaticField
accessible: private, name: derivedPrivateField
accessible: protected, name: derivedProtectedField
accessible: public, name: derivedPublicField
可以看到,getFields()
方法获取所有的 public 属性,包括继承来的;而 getDeclaredFields()
方法获取本类的所有属性,包括 public 属性、protected 属性和 private 属性。