getDeclaredField是可以获取一个类的所有字段. getField只能获取类的public 字段.
public Field getDeclaredField(String name)
throws NoSuchFieldException, SecurityException {
checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
Field field = searchFields(privateGetDeclaredFields(false), name);
if (field == null) {
throw new NoSuchFieldException(name);
}
return field;
}
rivate Field getField0(String name) throws NoSuchFieldException {
Field res = null;
// Search declared public fields
if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
return res;
}
getField其实调用的是getField0.他们最后都调用了searchFields.不过getDeclaredField传入的是privateGetDeclaredFields(false),getField传入的是privateGetDeclaredFields(true);
private Field[] privateGetDeclaredFields(boolean publicOnly) {
checkInitted();
Field[] res = null;
if (useCaches) {
clearCachesOnClassRedefinition();
if (publicOnly) {
if (declaredPublicFields != null) {
res = (Field[]) declaredPublicFields.get();
}
} else {
if (declaredFields != null) {
res = (Field[]) declaredFields.get();
}
}
可以看到传入条件为true的时候使用的是declaredPublicFields,意思是public字段 为false的时候使用的是declaredFields.
当然declaredFields和declaredPublicFields最终的来源是:
private native Field[] getDeclaredFields0(boolean publicOnly);