java 如何復制非空對象屬性值
java 復制非空對象屬性值
很多時候,我們需要通過對象拷貝,比如說VO類與數(shù)據(jù)庫實體bean類、更新時非空對象不更新,對同一對象不同數(shù)據(jù)分開存儲等
用于對象拷貝,spring 和 Apache都提供了相應(yīng)的工具類方法,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)
如果想對該注解進一步了解的話,那么可以去官網(wǎng)看英文文檔,文檔解釋的很清楚,在此不再贅述了
java對象屬性復制的幾種方式
1.使用java反射機制
獲取對象的屬性和get、set方法進行復制;
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);--第三個參數(shù)表示是否使用轉(zhuǎn)換器,false表示不使用,true表示使用 Converter converter = new CopyConverter();--自定義轉(zhuǎn)換器 beanCopier.copy(sourceObject, targetObject, converter);
轉(zhuǎn)換器(當源對象屬性類型與目標對象屬性類型不一致時,使用轉(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)過循環(huán)復制測試(源對象與目標對象各160個屬性):

- 第一種:Java反射通過判斷屬性類型,常用類型的屬性值都能復制,但是不優(yōu)化的前提下效率最慢;
- 第二種:屬性類型不同時無法復制,且效率相對較慢;
- 第三種:耗時最少,不使用轉(zhuǎn)換器時,屬性類型不同時無法復制,使用轉(zhuǎn)換器后,耗時會相對變長;
- 第四種:與第三種相似,但是耗時相對較長;
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Swagger3生成接口文檔的示例代碼
Swagger 是一個 RESTful API 的開源框架,它的主要目的是幫助開發(fā)者設(shè)計、構(gòu)建、文檔化和測試 Web API,本文給大家介紹了SpringBoot整合Swagger3生成接口文檔的流程,并通過代碼講解的非常詳細,需要的朋友可以參考下2024-04-04
Java中List轉(zhuǎn)Map List實現(xiàn)的幾種姿勢
本文主要介紹了Java中List轉(zhuǎn)Map List實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06
Java創(chuàng)建二叉搜索樹,實現(xiàn)搜索,插入,刪除的操作實例
下面小編就為大家分享一篇Java創(chuàng)建二叉搜索樹,實現(xiàn)搜索,插入,刪除的操作實例,具有很好的參考價值,希望對大家有所幫助2017-12-12
詳解Spring Boot實戰(zhàn)之Rest接口開發(fā)及數(shù)據(jù)庫基本操作
本篇文章主要介紹了Spring Boot實戰(zhàn)之Rest接口開發(fā)及數(shù)據(jù)庫基本操作,具有一定的參考價值,有興趣的可以了解一下2017-07-07

