深入java對象復(fù)制的分析
java本身提供了對象復(fù)制的能力,在java.lang.Object類中有clone方法,該方法是一個protected方法,在子類需要重寫此方法并聲明為public類型,而且還需實現(xiàn)Cloneable接口才能提供對象復(fù)制的能力,clone()是一個native方法,native方法的效率一般來說都是遠(yuǎn)高于java中的非native方法,對性能比較關(guān)心的話首先考慮這種方式,這種復(fù)制在網(wǎng)上有很多例子就不多寫了;在這要用的另一種方式——通過java的反射機(jī)制復(fù)制對象,這種方式效率可能會比clone()低,而且不支持深度復(fù)制以及復(fù)制集合類型,但通用性會提高很多,下邊是進(jìn)行復(fù)制的代碼:
private <T> T getBean(T TargetBean, T SourceBean) {
if (TargetBean== null) return null;
Field[] tFields = TargetBean.getClass().getDeclaredFields();
Field[] sFields = SourceBean.getClass().getDeclaredFields();
try {
for (Field field : tFields ) {
String fieldName = field.getName();
if (fieldName.equals("serialVersionUID")) continue;
if (field.getType() == Map.class) continue;
if (field.getType() == Set.class) continue;
if (field.getType() == List.class) continue;
for (Field sField : sFields) {
if(!sField .getName().equals(fieldName)){
continue;
}
Class type = field.getType();
String setName = getSetMethodName(fieldName);
Method tMethod = TargetBean.getClass().getMethod(setName, new Class[]{type});
String getName = getGetMethodName(fieldName);
Method sMethod = SourceBean.getClass().getMethod(getName, null);
Object setterValue = voMethod.invoke(SourceBean, null);
tMethod.invoke(TargetBean, new Object[]{setterValue});
}
}
} catch (Exception e) {
throw new Exception("設(shè)置參數(shù)信息發(fā)生異常", e);
}
return TargetBean;
}
該方法接收兩個參數(shù),一個是復(fù)制的源對象——要復(fù)制的對象,一個是復(fù)制的目標(biāo)對象——對象副本,當(dāng)然這個方法也可以在兩個不同對象間使用,這時候只要目標(biāo)對象和對象具有一個或多個相同類型及名稱的屬性,那么就會把源對象的屬性值賦給目標(biāo)對象的屬性。
相關(guān)文章
SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問的詳細(xì)過程
Spring Boot 底層都是采用 SpringData 的方式進(jìn)行統(tǒng)一處理各種數(shù)據(jù)庫,SpringData也是Spring中與SpringBoot、SpringCloud 等齊名的知名項目,下面看下SpringBoot Mybatis Druid數(shù)據(jù)訪問的詳細(xì)過程,感興趣的朋友一起看看吧2021-11-11利用Spring Cloud Config結(jié)合Bus實現(xiàn)分布式配置中心的步驟
這篇文章主要介紹了利用Spring Cloud Config結(jié)合Bus實現(xiàn)分布式配置中心的相關(guān)資料,文中通過示例代碼將實現(xiàn)的步驟一步步介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友下面來一起看看吧2018-05-05詳解JavaScript中的函數(shù)聲明和函數(shù)表達(dá)式
這篇文章主要介紹了詳解JavaScript中的函數(shù)聲明和函數(shù)表達(dá)式,是JS入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-08-08java并發(fā)學(xué)習(xí)-CountDownLatch實現(xiàn)原理全面講解
這篇文章主要介紹了java并發(fā)學(xué)習(xí)-CountDownLatch實現(xiàn)原理全面講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02