getDeclaredField()
getDeclaredField()和getField()方法都是获取字段的
getField 只能获取public的,包括从父类继承来的字段。
getDeclaredField 可以获取本类所有的字段,包括private的,但是不能获取继承来的字段。 (注: 这里只能获取到private的字段,但并不能访问该private字段的值,除非加上setAccessible(true))
因此在获取父类的私有属性时,要通过getSuperclass的之后再通过getDeclaredFiled获取
例子
// Java program to demonstrate the example
// of Field getDeclaredField (String field_name) method of Class
import java.lang.reflect.*;
public class GetDeclaredFieldOfClass {
public static void main(String[] args) throws Exception {
GetDeclaredFieldOfClass declare_field = new GetDeclaredFieldOfClass();
// Get Class
Class cl = declare_field.getClass();
// By using getDeclaredField() method is to get the field of
// the class
Field f = cl.getDeclaredField("i");
System.out.println("Declared Field: " + f.toString());
}
// Private Constructors
private GetDeclaredFieldOfClass() {
System.out.println("We are in private constructor");
}
// Public Constructors
public GetDeclaredFieldOfClass(int i) {
this.i = i;
}
int i = 100;
}
输出
We are in private constructor
Declared Field: int GetDeclaredFieldOfClass.i