java 如何復(fù)制非空對(duì)象屬性值
java 復(fù)制非空對(duì)象屬性值
很多時(shí)候,我們需要通過(guò)對(duì)象拷貝,比如說(shuō)VO類與數(shù)據(jù)庫(kù)實(shí)體bean類、更新時(shí)非空對(duì)象不更新,對(duì)同一對(duì)象不同數(shù)據(jù)分開(kāi)存儲(chǔ)等
用于對(duì)象拷貝,spring 和 Apache都提供了相應(yīng)的工具類方法,BeanUtils.copyProperties
但是對(duì)于非空屬性拷貝就需要自己處理了
在這里借用spring中org.springframework.beans.BeanUtils類提供的方法
copyProperties(Object source, Object target, String... ignoreProperties)
/** * Copy the property values of the given source bean into the given target bean, * ignoring the given "ignoreProperties". * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * <p>This is just a convenience method. For more complex transfer needs, * consider using a full BeanWrapper. * @param source the source bean * @param target the target bean * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException { copyProperties(source, target, null, ignoreProperties); /** * Copy the property values of the given source bean into the given target bean. * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * @param source the source bean * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ 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 && (ignoreList == 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); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } }
然后封裝一下得到以下方法
/** * @author zml2015 * @Email zhengmingliang911@gmail.com * @Time 2017年2月14日 下午5:14:25 * @Description <p>獲取到對(duì)象中屬性為null的屬性名 </P> * @param source 要拷貝的對(duì)象 * @return */ public static String[] getNullPropertyNames(Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<String>(); for (java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null) emptyNames.add(pd.getName()); } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } /** * @author zml2015 * @Email zhengmingliang911@gmail.com * @Time 2017年2月14日 下午5:15:30 * @Description <p> 拷貝非空對(duì)象屬性值 </P> * @param source 源對(duì)象 * @param target 目標(biāo)對(duì)象 */ public static void copyPropertiesIgnoreNull(Object source, Object target) { BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); }
測(cè)試方法就不提供了,自行測(cè)試即可
如果項(xiàng)目中使用的框架有Hibernate的話,則可以通過(guò)在實(shí)體類上添加下面兩條注解
@DynamicInsert(true) @DynamicUpdate(true)
如果想對(duì)該注解進(jìn)一步了解的話,那么可以去官網(wǎng)看英文文檔,文檔解釋的很清楚,在此不再贅述了
java對(duì)象屬性復(fù)制的幾種方式
1.使用java反射機(jī)制
獲取對(duì)象的屬性和get、set方法進(jìn)行復(fù)制;
2.使用spring-beans5.0.8包中的BeanUtils類
import org.springframework.beans.BeanUtils; SourceObject sourceObject = new SourceObject(); TargetObject targetObject = new TargetObject(); BeanUtils.copyProperties(sourceObject, targetObject);
3.使用cglib3.2.8包中的net.sf.cglib.beans.BeanCopier類
import net.sf.cglib.beans.BeanCopier; import net.sf.cglib.core.Converter; SourceObject sourceObject = new SourceObject(); TargetObject targetObject = new TargetObject(); BeanCopier beanCopier = BeanCopier.create(SourceObject.class, TargetObject.class, true);--第三個(gè)參數(shù)表示是否使用轉(zhuǎn)換器,false表示不使用,true表示使用 Converter converter = new CopyConverter();--自定義轉(zhuǎn)換器 beanCopier.copy(sourceObject, targetObject, converter);
轉(zhuǎn)換器(當(dāng)源對(duì)象屬性類型與目標(biāo)對(duì)象屬性類型不一致時(shí),使用轉(zhuǎn)換器):
import net.sf.cglib.core.Converter; import org.apache.commons.lang3.StringUtils; import java.math.BigDecimal; import java.util.Date; /** * Created by asus on 2019/7/12. */ public class CopyConverter implements Converter { @Override public Object convert(Object value, Class target, Object context) { { String s = value.toString(); if (target.equals(int.class) || target.equals(Integer.class)) { return Integer.parseInt(s); } if (target.equals(long.class) || target.equals(Long.class)) { return Long.parseLong(s); } if (target.equals(float.class) || target.equals(Float.class)) { return Float.parseFloat(s); } if (target.equals(double.class) || target.equals(Double.class)) { return Double.parseDouble(s); } if(target.equals(Date.class)){ while(s.indexOf("-")>0){ s = s.replace("-", "/"); } return new Date(s); } if(target.equals(BigDecimal.class)){ if(!StringUtils.isEmpty(s)&&!s.equals("NaN")){ return new BigDecimal(s); } } return value ; } } }
4.使用spring-core5.0.8包
中的org.springframework.cglib.beans.BeanCopier類(用法與第三種一樣)
import org.springframework.cglib.beans.BeanCopier; import org.springframework.cglib.core.Converter; SourceObject sourceObject = new SourceObject(); TargetObject targetObject = new TargetObject(); Converter converter = new SpringCopyConverter(); BeanCopier beanCopier = BeanCopier.create(SourceObject.class, TargetObject.class, true); beanCopier.copy(sourceObject, targetObject, converter);
經(jīng)過(guò)循環(huán)復(fù)制測(cè)試(源對(duì)象與目標(biāo)對(duì)象各160個(gè)屬性):
- 第一種:Java反射通過(guò)判斷屬性類型,常用類型的屬性值都能復(fù)制,但是不優(yōu)化的前提下效率最慢;
- 第二種:屬性類型不同時(shí)無(wú)法復(fù)制,且效率相對(duì)較慢;
- 第三種:耗時(shí)最少,不使用轉(zhuǎn)換器時(shí),屬性類型不同時(shí)無(wú)法復(fù)制,使用轉(zhuǎn)換器后,耗時(shí)會(huì)相對(duì)變長(zhǎng);
- 第四種:與第三種相似,但是耗時(shí)相對(duì)較長(zhǎng);
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實(shí)現(xiàn)讀取帶合并單元格的Excel
這篇文章主要為大家詳細(xì)介紹了java如何實(shí)現(xiàn)讀取帶合并單元格的Excel,文中的示例代碼講解詳細(xì), 感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12Java代碼審計(jì)的一些基礎(chǔ)知識(shí)你知道嗎
這篇文章主要介紹了基于Java的代碼審計(jì)功能的基礎(chǔ)知識(shí),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2021-09-09SpringBoot整合Swagger3生成接口文檔的示例代碼
Swagger 是一個(gè) RESTful API 的開(kāi)源框架,它的主要目的是幫助開(kāi)發(fā)者設(shè)計(jì)、構(gòu)建、文檔化和測(cè)試 Web API,本文給大家介紹了SpringBoot整合Swagger3生成接口文檔的流程,并通過(guò)代碼講解的非常詳細(xì),需要的朋友可以參考下2024-04-04Java中List轉(zhuǎn)Map List實(shí)現(xiàn)的幾種姿勢(shì)
本文主要介紹了Java中List轉(zhuǎn)Map List實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06Java創(chuàng)建二叉搜索樹(shù),實(shí)現(xiàn)搜索,插入,刪除的操作實(shí)例
下面小編就為大家分享一篇Java創(chuàng)建二叉搜索樹(shù),實(shí)現(xiàn)搜索,插入,刪除的操作實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助2017-12-12詳解Spring Boot實(shí)戰(zhàn)之Rest接口開(kāi)發(fā)及數(shù)據(jù)庫(kù)基本操作
本篇文章主要介紹了Spring Boot實(shí)戰(zhàn)之Rest接口開(kāi)發(fā)及數(shù)據(jù)庫(kù)基本操作,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07