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 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反射机制,获取对象的属性和值(包括所有父类)_第1张图片 

写法二 

    private static List getAllField2(Object bean) {
        Class clazz = bean.getClass();
        List 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

你可能感兴趣的:(------【反射机制】)