java map转化为对应的类

类对应的map中不一定有所有字段,每次把map转化为对应的类,总是重复操作,非常麻烦,所以可以创建一个遍历map的field的类来自动转化。

public T mapToObject(Map<String, String> fieldMap, T object) {

        Field[] fields = object.getClass().getDeclaredFields();

        for (Field field : fields) {

            field.setAccessible(true);

            try {
                if (fieldMap.get(field.getName()) != null) {

                    if (field.getType() == Integer.class)
                        field.set(object, Integer.valueOf(fieldMap.get(field.getName())));

                    if (field.getType() == Long.class)
                        field.set(object, Long.valueOf(fieldMap.get(field.getName())));

                    if (field.getType() == String.class)
                        field.set(object, fieldMap.get(field.getName()));

                    if (field.getType() == Date.class) {

                        field.set(object, string2Date(fieldMap.get(field.getName())));
                    }

                } else {
                    field.setAccessible(false);
                    continue;
                }
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            field.setAccessible(false);
        }
        return object;
    }


你可能感兴趣的:(java,map和类的转换)