Java實現不同的類的屬性之間相互賦值

來源:互聯網
上載者:User

標籤:類之間賦值   賦值   內省   反射   

在開發的時候可能會出現將一個類的屬性值,複製給另外一個類的屬性值,這在讀寫資料庫的時候,可能會經常的遇到 ,特別是對於一個有繼承關係的類的時候,我們需要重寫很多多餘的代碼,下面有一種簡單的方法實現該功能,

1、首先有兩個類,兩個類之間有相同的屬性名稱和類型,也有不同的屬性名稱很類型:

public class ClassTestCopy2 {    private int id;    private String name;    private String password;    private String sex;    private String age;    //get和set方法}
public class ClassTestCopy1 {    private int id;    private String name;    private String password;    //get和set方法}

2、下邊的就是實現該功能的方法體:

public static void Copy(Object source, Object dest) throws Exception {        // 擷取屬性        BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();        BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();        try {            for (int i = 0; i < sourceProperty.length; i++) {                for (int j = 0; j < destProperty.length; j++) {                    if (sourceProperty[i].getName().equals(destProperty[j].getName())) {                        // 調用source的getter方法和dest的setter方法                        destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));                        break;                    }                }            }        } catch (Exception e) {            throw new Exception("屬性複製失敗:" + e.getMessage());        }    }

3、下邊進行測試:

public static void main(String[] args) {        ClassTestCopy1 c1 = new ClassTestCopy1(1205030213, "name:xuliugen","password:123456");        ClassTestCopy2 c2 = new ClassTestCopy2();        try {            CopyBeanParamsTest.Copy(c1, c2);            System.out.println("-------------c1----------------");            System.out.println(c2.getId());            System.out.println(c2.getName());            System.out.println(c2.getPassword());            System.out.println(c2.getSex());            System.out.println(c2.getAge());        } catch (Exception e) {            e.printStackTrace();        }    }

4、測試結果如下:

可知具有相同屬性名稱和類型的屬性被賦值,剩下的沒有被匹配到的結果則為NUll;

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java實現不同的類的屬性之間相互賦值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.