Java反射机制,获取对象的属性和值(包括所有父类)

简单demo

public class Entity1 extends Entity2 {
    private String name1 ;
}

public class Entity2 extends Entity3{
    private BigDecimal bigDecimal2;
}

public class Entity3 {
    private Integer age3;
}

 

    public static void main(String[] args) {
        Entity1 entity1 = new Entity1();
        entity1.setName1("111");
        entity1.setBigDecimal2(new BigDecimal(222));
        entity1.setAge3(16);
        getAllField1(entity1);
    }

需要知道的点

1,根据当前class可以获取上级class:clazz.getSuperclass()

2,getField() 和 getDeclaredField() 的区别

  • getField() 只能获取public的,包括从父类继承来的字段
  • getDeclaredField() 可以获取当前类所有的字段,包括private的,但是不能获取继承来的字段

 写法一

 

    public static void getAllField1(Object bean) {
        Class<?> clazz = bean.getClass();
        List<Field> allField = new ArrayList<>();
        // 遍历往上获取父类,直至最后一个父类
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            // 获取当前类所有的字段
            Field[] field = clazz.getDeclaredFields();
            allField.addAll(new ArrayList<>(Arrays.asList(field)));
            for (Field f : field) {
                f.setAccessible(true);
                try {
                    System.out.println("属性名:" + f.getName());
                    System.out.println("属性类型:" + f.getGenericType());
                    System.out.println("属性值:" + f.get(bean).toString());
                    System.out.println();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

《Java反射机制,获取对象的属性和值(包括所有父类)》 

写法二 

    private static List<Field> getAllField2(Object bean) {
        Class clazz = bean.getClass();
        List<Field> fields = new ArrayList<>();
        while (clazz != null) {
            fields.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

 

参考来源于:

https://blog.csdn.net/sinat_28530913/article/details/72301506

https://blog.csdn.net/WZH577/article/details/94432056

    原文作者:_夜渐凉
    原文地址: https://blog.csdn.net/weixin_41888813/article/details/103875310
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞