Java反射实现List对象属性/值转换map

        List list = UserMapper.list();
            for (Object obj : list) {
                Map map = new HashMap<>();
                Method[] methods = obj.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        String name = method.getName().substring(3);
                        name = name.substring(0, 1).toLowerCase() +                                         name.substring(1);
                        String type = method.getReturnType().getName();
                        Object value = null;
                        // 时间类型格式化
                        if (method.invoke(obj) != null && type.equals("java.util.Date")) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                            Date date = new Date(method.invoke(obj).toString());
                            value = format.format(date);
                        } else {
                            value = method.invoke(obj);
                        }
                        map.put(name, value);
                    }
                }


                Map returnMap = new HashMap<>();
                // key值转换(请忽略)
                for (Map.Entry entry1 : mappingMap.entrySet()) {
                    boolean containsKey = map.containsKey(entry1.getKey());
                    if (containsKey) {
                        Object mapVal = map.get(entry1.getKey());
                        returnMap.put(entry1.getValue().toString(), mapVal);
                    } else {
                        returnMap.put(entry1.getKey(), "");
                    }
                }



                // bean通过反射获取属性/属性值
                Field fields[]=class对象.getClass().getDeclaredFields();
                String[] name=new String[fields.length];
                Object[] value=new Object[fields.length];
                try {
                    Field.setAccessible(fields, true);
                    for (int i = 0; i < name.length; i++) {
                    name[i] = fields[i].getName();
                    value[i] = fields[i].get(class对象);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

你可能感兴趣的:(java,后端,springboot,java,spring,boot,后端)