深入java對象複製的分析_java

來源:互聯網
上載者:User

java本身提供了對象複製的能力,在java.lang.Object類中有clone方法,該方法是一個protected方法,在子類需要重寫此方法並聲明為public類型,而且還需實現Cloneable介面才能提供對象複製的能力,clone()是一個native方法,native方法的效率一般來說都是遠高於java中的非native方法,對效能比較關心的話首先考慮這種方式,這種複製在網上有很多例子就不多寫了;在這要用的另一種方式——通過java的反射機制複製對象,這種方式效率可能會比clone()低,而且不支援深度複製以及複製集合類型,但通用性會提高很多,下邊是進行複製的代碼:

複製代碼 代碼如下:

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("設定參數資訊發生異常", e);
        }
        return TargetBean;
}


該方法接收兩個參數,一個是複製的來源物件——要複製的對象,一個是複製的目標對象——對象副本,當然這個方法也可以在兩個不同對象間使用,這時候只要目標對象和對象具有一個或多個相同類型及名稱的屬性,那麼就會把來源物件的屬性值賦給目標對象的屬性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.