본문 바로가기
개발 업무/JAVA

Domain Class -> Map형태로 변환

by 호크아이나인 2023. 2. 13.
public static Map<String, Object> bindObjectToMap(Object form) {
    Field[] keys = form.getClass().getDeclaredFields();
    Method[] methods = form.getClass().getDeclaredMethods();
    Map<String, Method> getMethods = new HashMap<String, Method>();
    String key = null;
    String name = null;
    for(Method one : methods) {
        name = one.getName();
        if(name.startsWith("set")) continue;
        key = name.substring(3).toLowerCase();
        getMethods.put(key, one);
    }
    Map<String, Object> ret = new HashMap<String, Object>();    
    Method method = null;
    for(Field one :  keys) {
        name = one.getName();
        name = name.replaceAll("_", "");
        if(!getMethods.keySet().contains(name.toLowerCase())) continue;
        method = getMethods.get(name.toLowerCase());
        try {
            Object result = method.invoke(form, new Object[]{ });              
            if(result != null) ret.put(name, result);
        } catch (IllegalAccessException e) {                
            System.out.println(e.getMessage() + " : " + method.getName());
        } catch (IllegalArgumentException e) {              
            System.out.println(e.getMessage() + " : " + method.getName());
        } catch (InvocationTargetException e) {            
            System.out.println(e.getMessage() + " : " + method.getName());
        }
    }
    return ret;    
}