在使用Java反射时,我对getFields
方法和getDeclaredFields
方法之间的区别感到有点困惑.
我读到getDeclaredFields
允许你访问类的所有字段,而getFields
只返回公共字段.如果是这样的话,你为什么不总是用getDeclaredFields
呢?
有人能详细说明一下这一点,并解释这两种方法之间的区别,以及何时/为什么你想使用一种方法而不是另一种方法?
在使用Java反射时,我对getFields
方法和getDeclaredFields
方法之间的区别感到有点困惑.
我读到getDeclaredFields
允许你访问类的所有字段,而getFields
只返回公共字段.如果是这样的话,你为什么不总是用getDeclaredFields
呢?
有人能详细说明一下这一点,并解释这两种方法之间的区别,以及何时/为什么你想使用一种方法而不是另一种方法?
100
整个类层次 struct 上的所有public
个字段.
100
所有字段,与其可访问性无关,但仅适用于当前类,而不适用于当前类可能继承的任何基类.
要使所有字段在层次 struct 中向上移动,我编写了以下函数:
public static Iterable<Field> getFieldsUpTo(@Nonnull Class<?> startClass,
@Nullable Class<?> exclusiveParent) {
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;
}
提供exclusiveParent
类是为了防止从Object
检索字段.如果你想要Object
个字段,可能是null
.
澄清一下,Lists.newArrayList
个来自番石榴.
仅供参考,以上代码在我ReflectionUtils年的LibEx项目中发布在GitHub上.