Java工具【十一】BeanTransferUtils

1、复制相应的字段到另一个实例中

2、将bean转换成map

3、根据class创建实例

public class BeanTransferUtils {
	
	private BeanTransferUtils(){
		//私有构造
	}
	
	public static <T, K> K transferColumn(T source, Class<T> sourceClazz, Class<K> targetClazz) throws CannaException {
        if (source == null) {
            return getInstance(targetClazz);
		}
        K targetBean = getInstance(targetClazz);

		BeanCopier.create(sourceClazz, targetClazz, false).copy(source, targetBean, null);
		return targetBean;
	}

    public static <T, K> List<K> transferColumn(List<T> sourceList, Class<T> sourceClazz, Class<K> targetClazz) throws CannaException {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyList();
        }


        List<K> result = new ArrayList<>();
        BeanCopier beanCopier = BeanCopier.create(sourceClazz, targetClazz, false);

        K targetBean;
        for (T source : sourceList) {
            targetBean = getInstance(targetClazz);
            beanCopier.copy(source, targetBean, null);
            result.add(targetBean);
        }
        return result;
    }

    public static <T> Map<String, Object> bean2Map(T bean) {
        if (bean == null) {
            return Collections.emptyMap();
        }

        BeanMap beanMap = BeanMap.create(bean);
        Map<String,Object> result = new HashMap<>(beanMap.size());
        result.putAll(beanMap);
        return result;
    }

	public static <T> T map2Bean(Map<String, Object> sourceMap, Class<T> targetClazz) {
		T bean = null;
		try {
			bean = targetClazz.newInstance();
			if (MapUtils.isNotEmpty(sourceMap)) {
				BeanMap beanMap = BeanMap.create(bean);
				beanMap.putAll(sourceMap);
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return bean;
	}

	public static <T> List<Map<String, Object>> beanList2Map(List<T> beanList) {
		if (CollectionUtils.isEmpty(beanList)) {
			return Collections.emptyList();
		}

		List<Map<String, Object>> list = new ArrayList<>(beanList.size());
        Map<String,Object> result;
		if (CollectionUtils.isNotEmpty(beanList)) {
			for (T bean : beanList) {
				if (bean == null) {
					continue;
				}

				BeanMap beanMap = BeanMap.create(bean);
                result = new HashMap<>(beanMap.size());
                result.putAll(beanMap);
				list.add(result);
			}
		}
		return list;
	}

	public static <T> T getInstance(Class<T> clazz) throws CannaException {
		try {
			return clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			log.info("", e);
			throw new CannaException(ToolsErrorType.REFLECT_FAIL);
		}
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值