对比新文件 |
| | |
| | | /** |
| | | * Copyright (c) 2018 人人开源 All rights reserved. |
| | | * |
| | | * https://www.renren.io |
| | | * |
| | | * 版权所有,侵权必究! |
| | | */ |
| | | |
| | | package com.iailab.framework.common.util.object; |
| | | |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.beans.BeanUtils; |
| | | |
| | | import java.lang.reflect.Field; |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | | import java.util.Collection; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 转换工具类 |
| | | * |
| | | * @author Mark sunlightcs@gmail.com |
| | | */ |
| | | 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; |
| | | } |
| | | /** |
| | | * 获取类的所有属性,包括父类 |
| | | * |
| | | * @param object |
| | | * @return |
| | | */ |
| | | public static Field[] getAllFields(Object object) { |
| | | Class<?> clazz = object.getClass(); |
| | | List<Field> fieldList = new ArrayList<>(); |
| | | while (clazz != null) { |
| | | fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); |
| | | clazz = clazz.getSuperclass(); |
| | | } |
| | | Field[] fields = new Field[fieldList.size()]; |
| | | fieldList.toArray(fields); |
| | | return fields; |
| | | } |
| | | } |