Java反射中getFields和getDeclaredFields有什么区别 [英] What is the difference between getFields and getDeclaredFields in Java reflection

查看:28
本文介绍了Java反射中getFields和getDeclaredFields有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 Java 反射时 getFields 方法和 getDeclaredFields 方法之间的区别有点困惑.

I'm a little confused about the difference between the getFields method and the getDeclaredFields method when using Java reflection.

我读到 getDeclaredFields 可让您访问该类的所有字段,而 getFields 仅返回公共字段.如果是这种情况,为什么不总是使用 getDeclaredFields?

I read that getDeclaredFields gives you access to all the fields of the class and that getFields only returns public fields. If this is the case, why wouldn't you just always use getDeclaredFields?

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

Can someone please elaborate on this, and explain the difference between the two methods, and when/why you would want to use one over the other?

推荐答案

getFields()

整个类层次结构中的所有 public 字段.

All the public fields up the entire class hierarchy.

getDeclaredFields()

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

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.

为了让所有字段都在层次结构中,我编写了以下函数:

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) {

   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.

The exclusiveParent class is provided to prevent the retrieval of fields from Object. It may be null if you DO want the Object fields.

澄清一下,Lists.newArrayList 来自 Guava.

To clarify, Lists.newArrayList comes from Guava.

仅供参考,以上代码已发布在我的 LibEx 项目中的 GitHub 上 ReflectionUtils.

FYI, the above code is published on GitHub in my LibEx project in ReflectionUtils.

这篇关于Java反射中getFields和getDeclaredFields有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆