参考 stackoverflow 社区的一个回答:
All the public
fields up the entire class hierarchy.
获取当前类对象的所有public属性,并且会自动父类遍历获取父类的 public 属性(如果有父类的话)
All the fields, regardless of their accessibility but only for the current class, not any base classes that the current class might be inheriting from.
获取当前类对象的所有属性(忽略访问限制),但是仅限遍历当前类 。
应用例子1:
(遍历当前类及其父类所有属性)
To get all the fields up the hierarchy, I have written the following function:
public static Iterable<Field> getFieldsUpTo(@Nonnull Class<?> startClass,
@Nullable Class<?> exclusiveParent) {
// The exclusiveParent class is provided to prevent the retrieval of fields from Object. It may be null if you DO want the Object fields.To clarify, Lists.newArrayList comes from Guava.
List<Field> currentClassFields = Lists.newArrayList(startClass.getDeclaredFields());
Class<?> parentClass = startClass.getSuperclass();
if (parentClass != null &&
(exclusiveParent == null || !(parentClass.equals(exclusiveParent)))) {
List<Field> parentClassFields =
(List<Field>) getFieldsUpTo(parentClass, exclusiveParent);
currentClassFields.addAll(parentClassFields);
}
return currentClassFields;
}
应用例子2:
This is useful to find a private
field from a superclass, for example. Also, if you want to modify its value, you can use it like this:
(不实例化某个父类对象的情况下,通过反射访问并改变其私有属性)
/**
* Sets {@code value} to the first {@link Field} in the {@code object} hierarchy, for the specified name
*/
public static void setField(Object object, String fieldName, Object value) throws Exception {
Field field = getField(object.getClass(), fieldName);
field.setAccessible(true);
field.set(object, value);
}