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); 可惜这是个native方法.感觉java就是很无奈,发现都是native方法档在路上.新闻热点
疑难解答