您好,登錄后才能下訂單哦!
小編給大家分享一下java怎么復制非空對象屬性值,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
很多時候,我們需要通過對象拷貝,比如說VO類與數據庫實體bean類、更新時非空對象不更新,對同一對象不同數據分開存儲等
用于對象拷貝,spring 和 Apache都提供了相應的工具類方法,BeanUtils.copyProperties
但是對于非空屬性拷貝就需要自己處理了
在這里借用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>獲取到對象中屬性為null的屬性名 </P> * @param source 要拷貝的對象 * @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> 拷貝非空對象屬性值 </P> * @param source 源對象 * @param target 目標對象 */ public static void copyPropertiesIgnoreNull(Object source, Object target) { BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); }
如果項目中使用的框架有Hibernate的話,則可以通過在實體類上添加下面兩條注解
@DynamicInsert(true) @DynamicUpdate(true)
如果想對該注解進一步了解的話,那么可以去官網看英文文檔,文檔解釋的很清楚,在此不再贅述了
獲取對象的屬性和get、set方法進行復制;
import org.springframework.beans.BeanUtils; SourceObject sourceObject = new SourceObject(); TargetObject targetObject = new TargetObject(); BeanUtils.copyProperties(sourceObject, targetObject);
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);--第三個參數表示是否使用轉換器,false表示不使用,true表示使用 Converter converter = new CopyConverter();--自定義轉換器 beanCopier.copy(sourceObject, targetObject, converter);
轉換器(當源對象屬性類型與目標對象屬性類型不一致時,使用轉換器):
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 ; } } }
中的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);
經過循環復制測試(源對象與目標對象各160個屬性):
第一種:Java反射通過判斷屬性類型,常用類型的屬性值都能復制,但是不優化的前提下效率最慢;
第二種:屬性類型不同時無法復制,且效率相對較慢;
第三種:耗時最少,不使用轉換器時,屬性類型不同時無法復制,使用轉換器后,耗時會相對變長;
第四種:與第三種相似,但是耗時相對較長;
看完了這篇文章,相信你對“java怎么復制非空對象屬性值”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。