Java常用对象操作工具代码实例
对象复制(反射法)
publicstaticvoidcopyProp(Objectfrom,Objectto,String...filterProp){ HashSetfilterSet=newHashSet (Arrays.asList(filterProp)); Class>fromc=from.getClass(); Class>toc=to.getClass(); List to_fields=newArrayList (); while(toc!=null){ to_fields.addAll(Arrays.asList(toc.getDeclaredFields())); toc=toc.getSuperclass(); } for(Fieldto_field:to_fields){ try{ if(filterSet.contains(to_field.getName())||"serialVersionUID".equals(to_field.getName())){ continue; } Fieldfrom_field=null; try{ from_field=fromc.getDeclaredField(to_field.getName()); }catch(Exceptione){ continue; } from_field.setAccessible(true); Objectvalue=from_field.get(from); if(value==null){ continue; } to_field.setAccessible(true); to_field.set(to,value); }catch(Exceptione){ e.printStackTrace(); } } }
- 只copy有值对象
- 不需要copy的属性用filterProp
- 是能过反射属性注入方法实现,所有属性的名称类型必须一样
对象复制(fastJson转换)
单个
publicstaticTbean2OtherBean(Objectbean,Class tClass){ returnJSON.parseObject(JSON.toJSONString(bean),tClass); }
列表
publicstaticList list2OtherList(ListoriginList,Class tClass){ List list=newArrayList<>(); if(!CollectionUtils.isEmpty(originList)){ for(Objectobj:originList){ Tt=bean2OtherBean(obj,tClass); list.add(t); } } returnlist; }
fastjson实现,属性不一样必须用注解
对象转MAP
publicstaticMap bean2map(Objectobj)throwsIllegalAccessException{ Map map=newHashMap<>(); Class>clazz=obj.getClass(); for(Fieldfield:clazz.getDeclaredFields()){ field.setAccessible(true); StringfieldName=field.getName(); Objectvalue=field.get(obj); map.put(fieldName,value); } return(Map )map; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。