久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Java常用對象操作工具代碼實例

瀏覽:21日期:2022-08-19 16:08:07

對象復制(反射法)

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;}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 波密县| 蕉岭县| 南丰县| 汝州市| 本溪市| 大埔区| 花莲县| 临泽县| 安多县| 岳阳县| 凤阳县| 乌兰浩特市| 伊通| 新兴县| 瑞安市| 武定县| 抚州市| 阆中市| 禹城市| 汉阴县| 成安县| 津市市| 蓬溪县| 吉木萨尔县| 乐亭县| 嘉义县| 稷山县| 达日县| 马公市| 武定县| 百色市| 沂水县| 正镶白旗| 伊川县| 岢岚县| 那曲县| 宜宾市| 定陶县| 五寨县| 平果县| 南开区|