Map 객체를 DTO 객체로 매핑하는 작업을 했었다.
작업 도중 가끔 오류가 나는 것을 발견하고 해결한 뒤에 정리 겸 적어본다.
일단 Map객체를 DTO 객체로 매핑하는 것은 DTO객체의 set 메소드를 사용하는 방법이 있다.
하지만 이런 방식을 사용하면 DTO의 필드가 많으면 많을 수록 코드의 길이가 길어지고
가독성 또한 많이 떨어질 것이다.
그래서 DTO의 필드를 뽑아낸 뒤에 map이 그 값을 key로 가지고 있을 때 DTO 객체로의 매핑을 하면 된다.
아래 예시 코드이다.
MemberDTO userVo = new MemberDTO();
for(Field field : userVo.getClass().getDeclaredFields()) {
field.setAccessible(true);
if(userMap.containsKey(field.getName())) {
try {
field.set(userVo, userMap.get(field.getName()));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
만약 여기서 MemberDTO가 어떤 클래스를 상속받은 클래스라면
상위 클래스의 필드도 뽑아와야 한다.
MemberDTOextend userVo = new MemberDTOextend();
for(Field field : getAllField(userVo.getClass())) {
field.setAccessible(true);
if(userMap.containsKey(field.getName())) {
try {
field.set(userVo, String.valueOf(userMap.get(field.getName())));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
public List<Field> getAllField(Class<?> clazz) {
List<Field> fields = new ArrayList<>();
while(clazz != null) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
clazz = clazz.getSuperclass();
}
return fields;
}