개발 업무/JAVA

특정 Domain Class와 Json Request 를 맵핑 시켜 주기

호크아이나인 2023. 2. 13. 23:30
Map<String, Object> regParam = (Map)param.get("regParam");
UserInfoVo userinfoVo = new UserInfoVo ();
ObjectUtils.bindMap(regParam, userinfoVo );

[ObjectUtils.class]
public static void bindMap(Map<String, Object> map, Object target) {
    Logger logger = LoggerFactory.getLogger(ObjectUtils.class);
    Map<String, Field> fieldMap = new HashMap<String, Field>();
    Field[] fields = target.getClass().getDeclaredFields();
    List<String> list = new ArrayList<String>();
    for (Field f : fields) list.add(f.getName().replaceAll("_", ""));
    for (String key : map.keySet() ) {  
        if(!list.contains(key)) continue;
        String fname = fields[list.indexOf(key)].getName();
        fieldMap.put(fname, fields[list.indexOf(key)]);
    }
    String methodName = null;
    Method method = null;
    for (String fn : map.keySet() ) {                      
        methodName = "set" + fn.substring(0, 1).toUpperCase() + fn.substring(1);
        try {
            method = target.getClass().getDeclaredMethod(methodName, fieldMap.get(fn).getType());
            method.invoke(target, map.get(fn));
        } catch (Exception e) {
            logger.debug("Can not invoke !! : " + methodName);
            e.printStackTrace();
        }
    }
}