最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java 如何復(fù)制非空對象屬性值

 更新時間:2021年09月01日 11:43:25   作者:zml_2015  
這篇文章主要介紹了java 如何復(fù)制非空對象屬性值的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

java 復(fù)制非空對象屬性值

很多時候,我們需要通過對象拷貝,比如說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對象屬性復(fù)制的幾種方式

1.使用java反射機制

獲取對象的屬性和get、set方法進行復(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);--第三個參數(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)復(fù)制測試(源對象與目標對象各160個屬性):

  • 第一種:Java反射通過判斷屬性類型,常用類型的屬性值都能復(fù)制,但是不優(yōu)化的前提下效率最慢;
  • 第二種:屬性類型不同時無法復(fù)制,且效率相對較慢;
  • 第三種:耗時最少,不使用轉(zhuǎn)換器時,屬性類型不同時無法復(fù)制,使用轉(zhuǎn)換器后,耗時會相對變長;
  • 第四種:與第三種相似,但是耗時相對較長;

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java 將List中的實體類按照某個字段進行分組并存放至Map中操作

    Java 將List中的實體類按照某個字段進行分組并存放至Map中操作

    這篇文章主要介紹了Java 將List中的實體類按照某個字段進行分組并存放至Map中操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • Java實用工具庫commons-lang3的使用

    Java實用工具庫commons-lang3的使用

    Apache?Commons?Lang?3是一個流行的Java實用工具庫,提供了對java.lang包的擴展,包括字符串操作、正則表達式處理、數(shù)字操作、日期和時間操作、隨機字符串生成和對象操作等功能
    2025-03-03
  • Java實現(xiàn)蘿卜勇者游戲的示例代碼

    Java實現(xiàn)蘿卜勇者游戲的示例代碼

    《蘿卜勇者》是由國內(nèi)玩家自制的一款獨立游戲,玩家扮演蘿卜勇士闖關(guān),打敗各種邪惡的敵人,獲得最后的勝利。本文將利用Java實現(xiàn)這一游戲,感興趣的可以了解一下
    2022-02-02
  • Java中Retry方法的簡單實現(xiàn)

    Java中Retry方法的簡單實現(xiàn)

    這篇文章主要介紹了Java中Retry方法的簡單實現(xiàn),Retry主要是利用Java的lambda表達式和線程接口實現(xiàn)有返回值和無返回值的重試,思考了下就寫了一個簡易Retry功能分享出來,需要的朋友可以參考下
    2024-01-01
  • IDEA遇到Internal error. Please refer to http://jb. gg/ide/critical-startup-errors的問題及解決辦法

    IDEA遇到Internal error. Please refer to http://jb. gg/ide/crit

    這篇文章主要介紹了IDEA遇到Internal error. Please refer to http://jb. gg/ide/critical-startup-errors的問題及解決辦法,本文通過圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下
    2020-08-08
  • Java中String類使用方法總結(jié)

    Java中String類使用方法總結(jié)

    這篇文章主要介紹了Java中String類的使用方法,文章簡單易懂,結(jié)尾有實例代碼幫助大家理解學(xué)習(xí),感興趣的朋友可以了解下
    2020-06-06
  • SpringBoot處理接口冪等性的兩種方法詳解

    SpringBoot處理接口冪等性的兩種方法詳解

    接口冪等性處理算是一個非常常見的需求了,我們在很多項目中其實都會遇到。本文為大家總結(jié)了兩個處理接口冪等性的兩種常見方案,需要的可以參考一下
    2022-06-06
  • MyBatis中常用的SQL語句詳解

    MyBatis中常用的SQL語句詳解

    MyBatis是一種優(yōu)秀的持久層框架,它支持定制化SQL、存儲過程以及高級映射,本文介紹了MyBatis中常用的SQL語句,包括基本查詢、多條件查詢、關(guān)聯(lián)查詢、分頁查詢、插入、更新、刪除等,并結(jié)合MyBatis的特性進行了說明
    2025-03-03
  • 關(guān)于IO密集型服務(wù)提升性能的三種方式

    關(guān)于IO密集型服務(wù)提升性能的三種方式

    這篇文章主要介紹了關(guān)于IO密集型服務(wù)提升性能的三種方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • 如何將SpringBoot項目打成?war?包并部署到Tomcat

    如何將SpringBoot項目打成?war?包并部署到Tomcat

    這篇文章主要介紹了如何將SpringBoot項目?打成?war?包?并?部署到?Tomcat,當前環(huán)境是windows,tomcat版本是8.5采用的springboot版本是2.2.3,本文結(jié)合實例代碼給大家詳細講解需要的朋友可以參考下
    2022-11-11

最新評論

乐都县| 宜宾县| 紫阳县| 武胜县| 龙南县| 乾安县| 吉隆县| 西华县| 湟源县| 天镇县| 来安县| 外汇| 布尔津县| 松阳县| 宜章县| 临沧市| 沙湾县| 拉萨市| 台北县| 建平县| 霞浦县| 阜新市| 财经| 马山县| 饶河县| 临安市| 专栏| 龙门县| 静宁县| 甘肃省| 托克托县| 临猗县| 河东区| 宜章县| 屏东市| 平远县| 固安县| 卓尼县| 梧州市| 密云县| 安达市|