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; }

輸出結果:spa

相關文章
相關標籤/搜索