Java常用對(duì)象操作工具代碼實(shí)例
對(duì)象復(fù)制(反射法)
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有值對(duì)象 不需要copy的屬性用filterProp 是能過反射屬性注入方法實(shí)現(xiàn),所有屬性的名稱類型必須一樣
對(duì)象復(fù)制(fastJson轉(zhuǎn)換)
單個(gè)
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實(shí)現(xiàn),屬性不一樣必須用注解
對(duì)象轉(zhuǎn)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;}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JS實(shí)現(xiàn)前端動(dòng)態(tài)分頁碼代碼實(shí)例2. 關(guān)于IDEA 2020.3 多窗口視圖丟失的問題3. javascript實(shí)現(xiàn)貪吃蛇小練習(xí)4. js實(shí)現(xiàn)碰撞檢測5. 一文帶你徹底理解Java序列化和反序列化6. 用Spring JMS使異步消息變得簡單7. PHP驗(yàn)證碼工具-Securimage8. Python 制作查詢商品歷史價(jià)格的小工具9. Python 利用Entrez庫篩選下載PubMed文獻(xiàn)摘要的示例10. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條

網(wǎng)公網(wǎng)安備