Skill/spring

convertDtoToMap

진열사랑 2023. 5. 18. 16:40

public Map<String, Object> convertDtoToMap(Object dto) {
     Map<String, Object> map = new HashMap<>();
                 Array.asList(dto.getClass().getDeclaredFeild()).stream().filter(field -> field.getAnnotation(ExcelFeild.class) != null)
.forEach(field -> {
        field.setAccessible(true);
        try {
             map.put(field.getName(), getValue(field.get(dto)));
        } catch (IllegalAccessException e) {
            log.error("convertDtoToMap Error : {}", e.getMessage());
            map.put(field.getName(), "");
        }
});

    return map;
}

private String getValue(Object value) {
        if (ObjectUtil.isEmpty(value)) return "";
        if (Number.class.isAssignableFrom(value.getClass())) {
                return NumberFormat.getInstance().format(value);
        } else if (value instanceof Boolean) {
                return String.valurOf(value);
        } else {
                return StringUtils.defaultString((String) value);
        }
}