Java 反射 getFields 和 getDeclareds 的区别

参考 stackoverflow 社区的一个回答:

https://stackoverflow.com/questions/16966629/what-is-the-difference-between-getfields-and-getdeclaredfields-in-java-reflectio#

 

getFields()

All the public fields up the entire class hierarchy.

获取当前类对象的所有public属性,并且会自动父类遍历获取父类的 public 属性(如果有父类的话)

 

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.

获取当前类对象的所有属性(忽略访问限制),但是仅限遍历当前类 。

 

应用例子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);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值