问题

使用Java反射时,我对使用getFields方法和getDeclaredFields方法之间的区别感到有些困惑。

我读到了5313174723,你可以访问该类的所有字段,而且,getFields只返回公共字段。如果是这种情况,你为什么不总是使用getDeclaredFields

有人可以详细说明这一点,并解释两种方法之间的区别,以及何时/为什么要使用其中一种方法?


#1 热门回答(191 赞)

getFields()

所有public都在整个类层次结构中。

getDeclaredFields()

所有字段,无论其可访问性如何,但仅限于当前类的**,而不是当前类可能继承的任何基类。**

###在层次结构中获取所有字段

我写了以下函数:

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;
}

提供了exclusiveParentclass以防止从Object中检索字段。如果你想要Object字段,可能是null

澄清,Lists.newArrayList来自番石榴。

###更新

仅供参考,上述代码发布于GitHub的myLibExproject inReflectionUtils


#2 热门回答(5 赞)

如前所述,Class.getDeclaredField(String)通常会查看你称之为Class的字段。

如果要在Class层次结构中搜索aField,可以使用以下简单函数:

/**
 * Returns the first {@link Field} in the hierarchy for the specified name
 */
public static Field getField(Class<?> clazz, String name) {
    Field field = null;
    while (clazz != null && field == null) {
        try {
            field = clazz.getDeclaredField(name);
        } catch (Exception e) {
        }
        clazz = clazz.getSuperclass();
    }
    return field;
}

例如,这对于从超类中查找aprivate字段很有用。此外,如果要修改其值,可以像这样使用它:

/**
 * 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);
}

#3 热门回答(4 赞)

public Field[] getFields() throws SecurityException
返回一个包含Field对象的数组,这些对象反映此Class对象所表示的类或接口的所有可访问公共字段。返回的数组中的元素没有排序,也没有任何特定的顺序。如果类或接口没有可访问的公共字段,或者它表示数组类,基本类型或void,则此方法返回长度为0的数组。

具体来说,如果此Class对象表示一个类,则此方法返回此类及其所有超类的公共字段。如果此Class对象表示接口,则此方法返回此接口及其所有超接口的字段。

此方法不反映数组类的隐式长度字段。用户代码应该使用类Array的方法来操作数组。

public Field[] getDeclaredFields() throws SecurityException
返回Field对象的数组,反映由此Class对象表示的classor接口声明的所有字段。这包括公共,受保护,默认(包)访问和私有字段,butexcludes inheritedfields。返回的数组中的元素没有排序,也没有任何特定的顺序。如果类或接口声明没有字段,或者此Class对象表示基本类型,数组类或void,则此方法返回长度为0的数组。

如果我需要所有父类的所有字段呢?需要一些代码,例如fromhttps://stackoverflow.com/a/35103361/755804

public static List<Field> getAllModelFields(Class aClass) {
    List<Field> fields = new ArrayList<>();
    do {
        Collections.addAll(fields, aClass.getDeclaredFields());
        aClass = aClass.getSuperclass();
    } while (aClass != null);
    return fields;
}

原文链接