java 反射之获取泛型对象的所有字段与对应的值(包括父类的)

上代码:

public static void main(String[] args) throws IntrospectionException {
        SysUser obj = new SysUser();
        obj.setId(1L);
        obj.setUserName("测试");
        obj.setCreatedDate(LocalDateTime.now());

        Class<?> clazz = SysUser.class;
        Field[] tableFields = clazz.getDeclaredFields();
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz.equals(Object.class)) {
            System.out.println("没有父类");
        } else {
            Field[] tableSuperFields = superClazz.getDeclaredFields();
            Field[] superFields = new Field[tableFields.length + tableSuperFields.length];
            System.arraycopy(tableFields, 0, superFields, 0, tableFields.length);
            System.arraycopy(tableSuperFields, 0, superFields, tableFields.length, tableSuperFields.length);
            Field[] allFields = getSuperClassFields(superFields, superClazz);
            for (int i = 0; i < allFields.length; i++) {
                PropertyDescriptor pd = new PropertyDescriptor(allFields[i].getName(), clazz);
                Method getMethod = pd.getReadMethod();//获得get方法
                Object fieldValue = ReflectionUtils.invokeMethod(getMethod, obj);
                if(fieldValue == null){
                    continue;
                }

                System.out.println(allFields[i].getName() + "的值:" +  fieldValue.toString());
            }
        }
    }

//获取父类的所有字段
private static Field[] getSuperClassFields(Field[] tableFields, Class<?> clazz) { Class<?> superClazz = clazz.getSuperclass(); if (superClazz.equals(Object.class)) { return tableFields; } Field[] tableSuperFields = superClazz.getDeclaredFields(); Field[] c = new Field[tableFields.length + tableSuperFields.length]; System.arraycopy(tableFields, 0, c, 0, tableFields.length); System.arraycopy(tableSuperFields, 0, c, tableFields.length, tableSuperFields.length); getSuperClassFields(c, superClazz); return c; }

输出结果:

 

posted @ 2019-02-20 15:23  一问三不知。  阅读(6011)  评论(0编辑  收藏  举报