본문 바로가기
  • A space that records me :)
Language/JAVA

[JAVA] Map to Object, Object to Map

by yjkim_97 2020. 11. 19.

Object를 Map으로 변환, Map을 Object로 변환하는 Util

 

사용 객체

  • PropertyDescriptor
  • Method

Object method invoke (setMethod)

private static void invokeMethodSiently(Object obj, Method m, Object val) {
    try
    {
          m.invoke(obj, val);
    } catch (Exception ex)
    {
    	  LOGGER.error(ex.getMessage(), ex);
    }
}

Object method invoke (getMethod)

	private static Object invokeGetMethod(Object o, Method m) {
		Object obj = new Object();
		try
		{
			obj = m.invoke(o);
			if(ObjectUtils.isEmpty(obj)) {
				obj = StringUtils.EMPTY;
			}
		}catch (Exception e)
		{
			LOGGER.error(e.getMessage(), e);
			return StringUtils.EMPTY;
		}
		
		return obj;
	}

 

Object를 Map으로 변환 (getMethod사용)

	public static Map<String, String> converObjectToMap(Object obj){
		try {
			List<PropertyDescriptor> propertyDescriptors = ReflectionUtil.getPropertyDescriptors(obj.getClass());
			Map<String, String> resultMap = new HashMap<String, String>();
			for(PropertyDescriptor pd : propertyDescriptors) {
				resultMap.put(pd.getName(), invokeGetMethod(obj, pd.getReadMethod()).toString());
			}
			
			return resultMap;
		} catch (IllegalArgumentException e) {
			return null;
		}
			 
	}

Map을 Object로 변환 (setMethod)

	public static Object convertMapToObject(Map<String, String> map, Object objClass) {
		List<PropertyDescriptor> propertyDescriptors = ReflectionUtil.getPropertyDescriptors(objClass.getClass());
		Map<String, PropertyDescriptor> namePdMap = new HashMap<>();

		for (PropertyDescriptor pd : propertyDescriptors) {
			String pdName = pd.getName();
			namePdMap.put(pdName, pd);
		}

		for (Map.Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String val = entry.getValue();

			if (StringUtils.isEmpty(val )) {
				continue;
			}

			PropertyDescriptor pd = namePdMap.get(key);
			
			if (pd == null) {
				LOGGER.debug(" There is no key. >> " + key);
				continue;
			}
			Class<?> propertyType = pd.getPropertyType();
			
			Object resultValue = null;

			if (ReflectionUtil.isPrimitive(propertyType)) {
				if(propertyType == Boolean.class) {
					if(val.equals("true") || val.equals("1")) {
						val = "true";
					}else {
						val = "false";
					}
				}
				resultValue = ReflectionUtil.convertString2PrimitiveTypeValue(propertyType, val);
			} else if (CpnCodes.Common.class.isAssignableFrom(propertyType)) {
				Class clz = propertyType;
				resultValue = CpnCodes.enumByValue(clz, val);
				if (resultValue == null) {
					resultValue = CpnCodes.enumByCode(clz, NumberUtils.toLong(val, 0));
				}
			} else if (Date.class.isAssignableFrom(propertyType))
			{
				if(val.matches(CpnConstants.REX_DATE)) {					
					resultValue = DateUtil.parseDate(val, CpnConstants.PTN_DATE);
				}else if (val.matches(CpnConstants.REX_TIMESTAMP)){
					resultValue = DateUtil.parseDate(val, CpnConstants.PTN_TIMESTAMP);
				}
			}
			
			if (resultValue != null) {
				invokeMethodSiently(objClass, pd.getWriteMethod(), resultValue);
			}
		}

		LOGGER.debug("Map To Model result >> " + objClass);
		return objClass;
	}

 


[util] MapToModsl.java - 전체 코드

package com.kt.tbb.iptv.coupon.framework.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kt.tbb.iptv.coupon.framework.CpnCodes;
import com.kt.tbb.iptv.coupon.framework.CpnCodes.Common;
import com.kt.tbb.iptv.coupon.framework.CpnConstants;
import com.kt.tbb.iptv.coupon.framework.log.CpnLoggers;

public class MapToModel {
	private static final Logger LOGGER = LoggerFactory.getLogger(MapToModel.class);

	private static void invokeMethodSiently(Object obj, Method m, Object val) {
		try
		{
			m.invoke(obj, val);
		} catch (Exception ex)
		{
			LOGGER.error(ex.getMessage(), ex);
		}
	}
	private static Object invokeGetMethod(Object o, Method m) {
		Object obj = new Object();
		try
		{
			obj = m.invoke(o);
			if(ObjectUtils.isEmpty(obj)) {
				obj = StringUtils.EMPTY;
			}
		}catch (Exception e)
		{
			LOGGER.error(e.getMessage(), e);
			return StringUtils.EMPTY;
		}
		
		return obj;
	}

	public static Object convertMapToObject(Map<String, String> map, Object objClass) {
		List<PropertyDescriptor> propertyDescriptors = ReflectionUtil.getPropertyDescriptors(objClass.getClass());
		Map<String, PropertyDescriptor> namePdMap = new HashMap<>();

		for (PropertyDescriptor pd : propertyDescriptors) {
			String pdName = pd.getName();
			namePdMap.put(pdName, pd);
		}

		for (Map.Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String val = entry.getValue();

			if (StringUtils.isEmpty(val )) {
				continue;
			}

			PropertyDescriptor pd = namePdMap.get(key);
			
			if (pd == null) {
				LOGGER.debug(" There is no key. >> " + key);
				continue;
			}
			Class<?> propertyType = pd.getPropertyType();
			
			Object resultValue = null;

			if (ReflectionUtil.isPrimitive(propertyType)) {
				if(propertyType == Boolean.class) {
					if(val.equals("true") || val.equals("1")) {
						val = "true";
					}else {
						val = "false";
					}
				}
				resultValue = ReflectionUtil.convertString2PrimitiveTypeValue(propertyType, val);
			} else if (CpnCodes.Common.class.isAssignableFrom(propertyType)) {
				Class clz = propertyType;
				resultValue = CpnCodes.enumByValue(clz, val);
				if (resultValue == null) {
					resultValue = CpnCodes.enumByCode(clz, NumberUtils.toLong(val, 0));
				}
			} else if (Date.class.isAssignableFrom(propertyType))
			{
				if(val.matches(CpnConstants.REX_DATE)) {					
					resultValue = DateUtil.parseDate(val, CpnConstants.PTN_DATE);
				}else if (val.matches(CpnConstants.REX_TIMESTAMP)){
					resultValue = DateUtil.parseDate(val, CpnConstants.PTN_TIMESTAMP);
				}
			}
			
			if (resultValue != null) {
				invokeMethodSiently(objClass, pd.getWriteMethod(), resultValue);
			}
		}

		LOGGER.debug("Map To Model result >> " + objClass);
		return objClass;
	}
	public static Map<String, String> converObjectToMap(Object obj){
		try {
			List<PropertyDescriptor> propertyDescriptors = ReflectionUtil.getPropertyDescriptors(obj.getClass());
			Map<String, String> resultMap = new HashMap<String, String>();
			for(PropertyDescriptor pd : propertyDescriptors) {
				resultMap.put(pd.getName(), invokeGetMethod(obj, pd.getReadMethod()).toString());
			}
			
			return resultMap;
		} catch (IllegalArgumentException e) {
			return null;
		}
			 
	}
	
	private static void classInvoke(Method method, Object objClass, Class cls, String param)
	{
		try
		{
			CpnLoggers.TC_LOGGER.info(method.getName());
			CpnLoggers.TC_LOGGER.info("{}", cls);
			CpnLoggers.TC_LOGGER.info("---------------------------------------");
			if (cls == Integer.class || cls == int.class)
			{
				method.invoke(objClass, Integer.valueOf(param));
			} else if (cls == Long.class)
			{
				method.invoke(objClass, Long.valueOf(param));
			} else if (cls == String.class)
			{
				method.invoke(objClass, param);
			} else if (Common.class.isAssignableFrom(cls))
			{
				method.invoke(objClass, CpnCodes.enumByValue(cls, param));
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
	}
}

참고 (ReflectionUtil, Method, PropertyDescriptor)

2020/11/30 - [IT story/JAVA] - [JAVA] ReflectionUtil

 

[JAVA] ReflectionUtil

[util] - ReflectionUtil.java package com.kt.tbb.iptv.coupon.framework.util; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.Pr..

yjkim97.tistory.com

2020.11.30 - [IT story/JAVA] - [JAVA] PropertyDescriptor 클래스

 

[JAVA] PropertyDescriptor 클래스

하위클래스 : IndexedPropertyDescriptor 상위클래스 : FeatureDescriptor PropertyDescriptor는 Object의 한쌍의 접근자 메서드(getMethod, setMethod)의 속성을 다루는 클래스이다. A PropertyDescriptor descri..

yjkim97.tistory.com