大家在做java開發時,肯定會遇到api層參數對象傳遞給服務層,或者把service層的對象傳遞給dao層,他們之間又不是同一個類型對象,但字段又是一樣,如果還是用普通的get、set方式來處理話,比較繁瑣,.... 那么你來跟我學....."天下武功,唯快不破"===>要的就是快....
1.使用get/set不用說了,字段一多腦殼大....
2.BeanCopier 使用了cglib的修改字節碼,真的是動態Read Writer getter/setter 快的一逼啊 源碼過於簡單 直接上代碼 我使用的最基本的,大家可以自定義Converter,定以后完全
按照Converter轉換
需要注意的是:
1.當源類和目標類的屬性名稱、類型都相同,拷貝結果棒棒噠。
2.當源對象和目標對象的屬性名稱相同、類型不同,那么名稱相同而類型不同的屬性不會被拷貝。另外注意,原始類型(int,short,char)和 他們的包裝類型,在這里都被當成了不同類型。因此不會被拷貝。
3.源類或目標類的setter比getter少,拷貝沒問題,此時setter多余,但是不會報錯。
4.源類和目標類有相同的屬性(兩者的getter都存在),但是目標類的setter不存在, 此時會拋出NullPointerException(這個在高版本bug已經修改測試通過,我使用的49.0)
/** * @author LiJing * @ClassName: BeanCopyUtils * @Description: 基於BeanCopier的屬性拷貝 * @date 2019/4/17 9:15 * * 凡是和反射相關的操作,基本都是低性能的。凡是和字節碼相關的操作,基本都是高性能的。 * <p/> */ @Slf4j public class BeanCopyUtils { /** * 創建過的BeanCopier實例放到緩存中,下次可以直接獲取,提升性能 */ private static final Map<String, BeanCopier> BEAN_COPIERS = new ConcurrentHashMap<>(); /** * 該方法沒有自定義Converter,簡單進行常規屬性拷貝 * * @param srcObj 源對象 * @param destObj 目標對象 */ public static void copy(final @NotNull Object srcObj, final @NotNull Object destObj) { String key = genKey(srcObj.getClass(), destObj.getClass()); BeanCopier copier; if (!BEAN_COPIERS.containsKey(key)) { copier = BeanCopier.create(srcObj.getClass(), destObj.getClass(), false); BEAN_COPIERS.put(key, copier); } else { copier = BEAN_COPIERS.get(key); } copier.copy(srcObj, destObj, null); } private static String genKey(Class<?> srcClazz, Class<?> destClazz) { return srcClazz.getName() + destClazz.getName(); } }
3.接下來再來玩一個org.springframework.beans.BeanUtils,這個比較騷,使用反射,反射就比較慢了,要加載字節碼,反編譯,再實例化,再映射屬性.....來來上二斤代碼,先吃着 有用的地方不多
大家看着用哈<copyProperties>其實有這個方法就夠了
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * @author LiJing * @ClassName: BeanUtils * @Description: 屬性拷貝工具類 * @date 2018/4/10 11:54 */ @Slf4j public class MyBeanUtils extends BeanUtils { /** * 從org.springframework.beans.BeanUtils類中直接復制過來 * * @param source * @param target * @throws BeansException */ public static void copyProperties(Object source, Object target) throws BeansException { copyProperties(source, target, null, (String[]) null); } /** * 從org.springframework.beans.BeanUtils類中直接復制過來,修改部分代碼,不為null才復制 * * @param source * @param target * @param editable * @param ignoreProperties * @throws BeansException */ private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); // 判斷被復制的屬性是否為null, 如果不為null才復制 if (value != null) { if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException( "不能拷貝屬性 '" + targetPd.getName() + "' 從原對象給目標對象,詳細原因見:", ex); } } } } } } /** * 構造函數. */ public MyBeanUtils() { throw new RuntimeException("this is a util class,can not instance"); } }
4.還有很多屬性拷貝的方法例如org.apache.commons.beanutils.BeanUtils的copyProperties(Object dest, Object src)這里不舉例了 類似於Spring的屬性拷貝
5.還有使用easymapper來進行對象映射,但在項目中存在不穩性,偶爾出現映射不上的問題,會報異常com.baidu.unbiz.easymapper.exception.MappingException,大家可自行研究
其實有很多種方法進行屬性拷貝的,例如dozer等等 下面看下測試性能吧:以:萬級進行測試,我覺得Cglib太給力了.可以在遇到屬性拷貝瓶頸時考慮.當然他們各有優點哈,功能也不盡相同.還需要多使用體會.
輸出結果:手動Copy > cglibCopy > springBeanUtils > apachePropertyUtils > apacheBeanUtils 可以理解為: 手工復制 > cglib > 反射 > Dozer。
類型Framework |
測試性能(10000調用次)time |
Pure get/set |
10ms |
Easy mapper |
46ms |
Cglib Beancopier |
11ms |
Spring BeanUtils |
94ms |
Apache BeanUtils |
249ms |
Apache PropertieyUtils |
130ms |
Dozer |
770ms |