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

查看:131
本文介绍了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()

getFields()

所有 public 填充整个类层次结构。

All the public fields up the entire class hierarchy.

getDeclaredFields()

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 中检索字段。如果你想要对象字段,它可能是 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上发布href =https://github.com/dancerjohn/LibEx/blob/master/libex/src/main/java/org/libex/reflect/ReflectionUtils.java =noreferrer> ReflectionUtils 。

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

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

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