Java对象操作工具

对象复制(反射法)

public static void copyProp(Object from, Object to, String... filterProp)  {
        HashSet<String> filterSet = new HashSet<String>(Arrays.asList(filterProp));
        Class<?> fromc = from.getClass();
        Class<?> toc = to.getClass();
        List<Field> to_fields = new ArrayList<Field>() ;
        while (toc != null) {
            to_fields.addAll(Arrays.asList(toc.getDeclaredFields()));
            toc = toc.getSuperclass();
        }
        for (Field to_field : to_fields) {
            try{
                if (filterSet.contains(to_field.getName())||"serialVersionUID".equals(to_field.getName())) {
                    continue;
                }
                Field from_field = null;
                try{
                    from_field = fromc.getDeclaredField(to_field.getName());
                }catch (Exception e){
                    continue;
                }
                from_field.setAccessible(true);
                Object value = from_field.get(from);
                if(value==null){
                    continue;
                }
                to_field.setAccessible(true);
                to_field.set(to, value);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
  • 只copy有值对象
  • 不需要copy的属性用filterProp
  • 是能过反射属性注入方法实现,所有属性的名称类型必须一样

对象复制(fastJson转换)

单个

public static <T> T bean2OtherBean(Object bean, Class<T> tClass){
	return JSON.parseObject(JSON.toJSONString(bean),tClass);
}

列表

public static <T> List<T> list2OtherList(List originList, Class<T> tClass){
	List<T> list = new ArrayList<>();
	if(!CollectionUtils.isEmpty(originList)){
		for (Object obj : originList) {
			T t = bean2OtherBean(obj,tClass);
			list.add(t);
		}
	}
	return list;
}
  • fastjson实现,属性不一样必须用注解

对象转MAP

public static <K,V> Map<K,V> bean2map(Object obj) throws IllegalAccessException {
	Map<String, Object> map = new HashMap<>();
	Class<?> clazz = obj.getClass();
	for (Field field : clazz.getDeclaredFields()) {
		field.setAccessible(true);
		String fieldName = field.getName();
		Object value = field.get(obj);
		map.put(fieldName, value);
	}
	return (Map<K, V>) map;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值