티스토리 뷰

우연히 어느 개발커뮤니티 사이트에 올라온 글을 보다 VO를 Map으로 변환해야 하는 질문글이 올라왔는데
그 방법이 궁금해서 이참에 Reflection을 이용하여 양방향으로 원하는 타입에 맞게 변환하는 코드를 작성해 보았습니다.

 

VO <-> Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.lang.reflect.Field;
import java.util.*;
 
public class ConvertUtils {
    private ConvertUtils() {}
    
    // VO -> Map
    public static Map<String, Object> convertToMap(Object obj) {
        try {
            if (Objects.isNull(obj)) {
                return Collections.emptyMap();
            }
            Map<String, Object> convertMap = new HashMap<>();
 
            Field[] fields = obj.getClass().getDeclaredFields();
 
            for (Field field : fields) {
                field.setAccessible(true);
                convertMap.put(field.getName(), field.get(obj));
            }
            return convertMap;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    
    // Map -> VO
    public static <T> T convertToValueObject(Map<String, Object> map, Class<T> type) {
        try {
            if (Objects.isNull(type)) {
                throw new NullPointerException("Class cannot be null");
            }
            if (Objects.isNull(map) || map.isEmpty()) {
                throw new IllegalArgumentException("map is null or empty");
            }
 
            T instance = type.getConstructor().newInstance();
            Field[] fields = type.getDeclaredFields();
 
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                for (Field field : fields) {
                    if (entry.getKey().equals(field.getName())) {
                        field.setAccessible(true);
 
                        Object value = Objects.isNull(entry.getValue()) && field.getType().isPrimitive()
                                ? getDefaultValue(field.getType())
                                : map.get(field.getName());
 
                        field.set(instance, value);
                        break;
                    }
                }
            }
            return instance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    private static Object getDefaultValue(Class<?> type) {
        switch (type.getName()) {
            case "byte"case "short"case "int"return 0;
            case "long"    : return 0L;
            case "float"   : return 0.0f;
            case "double"  : return 0.0d;
            case "char"    : return '\u0000';
            case "boolean" : return false;
        }
        return null;
    }
}
cs

결과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Map;
 
public class Main {
    public static void main(String[] args) {
        test1();
    }
 
    private static void test1() {
        Student student = new Student();
        student.setName("김종현");
        student.setGender("남성");
        student.setAddress("서울");
        student.setPhoneNo("010-1111-2222");
        student.setAge(29);
 
        Map<String, Object> convertMap = ConvertUtils.convertToMap(student);
        System.out.println("VO -> Map");
        System.out.println(convertMap);
 
        Student convertValueObject = ConvertUtils.convertToValueObject(convertMap, Student.class);
        System.out.println("Map -> VO");
        System.out.println(convertValueObject);
    }
}
cs

 

 

List<VO> <-> List<Map>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
 
public class ConvertUtils {
    private ConvertUtils() {}
 
    public static List<Map<String, Object>> convertToMaps(List<?> list) {        
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        return list.stream()
                .map(ConvertUtils::convertToMap)
                .collect(Collectors.toList());
    }
 
    public static <T> List<T> convertToValueObjects(List<Map<String, Object>> list, Class<T> type) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        List<T> convertList = new ArrayList<>(list.size());
 
        for (Map<String, Object> map : list) {
            convertList.add(ConvertUtils.convertToValueObject(map, type));
        }
        return convertList;
    }
}
cs

결과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
public class Main {
    public static void main(String[] args) {
        test2();
    }
    
    private static void test2() {
        List<Student> students = new ArrayList<>();
 
        Student student = new Student();
        student.setName("김종현");
        student.setGender("남성");
        student.setAddress("서울");
        student.setPhoneNo("010-1111-2222");
        student.setAge(29);
        students.add(student);
 
        student = new Student();
        student.setName("홍길동");
        student.setGender("남성");
        student.setAddress("서울");
        student.setPhoneNo("010-3333-4444");
        student.setAge(29);
        students.add(student);
 
        List<Map<String, Object>> convertMaps = ConvertUtils.convertToMaps(students);
        System.out.println("List<VO> -> List<Map>");
        convertMaps.forEach(System.out::println);
 
        List<Student> convertValueObjects = ConvertUtils.convertToValueObjects(convertMaps, Student.class);
        System.out.println("List<Map> -> List<VO>");
        convertValueObjects.forEach(System.out::println);
    }
}
cs

 

참고로 Map에서 VO로 변환할 때 두번째 인자에 들어가는 Class 타입엔 해당 Class의 기본 생성자가 있어야한다.

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함