本文主要是介绍【第012篇】Java工具类之对象转换工具,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package io.renren.common.utils;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;import java.util.ArrayList;
import java.util.Collection;
import java.util.List;/**
* 对象转换工具类
*/
public class ConvertUtils {private static Logger LOGGER = LoggerFactory.getLogger(ConvertUtils.class);// 对象转换public static <T> T sourceToTarget(Object source, Class<T> target){if(source == null){return null;}T targetObject = null;try {targetObject = target.newInstance();BeanUtils.copyProperties(source, targetObject);} catch (Exception e) {LOGGER.error("convert error ", e);}return targetObject;}public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){if(sourceList == null){return null;}List targetList = new ArrayList<>(sourceList.size());try {for(Object source : sourceList){T targetObject = target.newInstance();BeanUtils.copyProperties(source, targetObject);targetList.add(targetObject);}}catch (Exception e){LOGGER.error("convert error ", e);}return targetList;}
}
调用:
ProcessBizRouteDTO processBizRouteDTO = new ProcessBizRouteDTO();
ProcessBizRouteAndProcessInstanceDTO dto = ConvertUtils.sourceToTarget(processBizRouteDTO, ProcessBizRouteAndProcessInstanceDTO.class);
这篇关于【第012篇】Java工具类之对象转换工具的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!