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

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

瀏覽:6日期: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
相關文章:
国产综合久久一区二区三区