溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java實(shí)現(xiàn)不同的類的屬性之間相互賦值

發(fā)布時(shí)間:2020-09-09 18:31:47 來源:腳本之家 閱讀:168 作者:徐劉根 欄目:編程語言

在開發(fā)的時(shí)候可能會(huì)出現(xiàn)將一個(gè)類的屬性值,復(fù)制給另外一個(gè)類的屬性值,這在讀寫數(shù)據(jù)庫(kù)的時(shí)候,可能會(huì)經(jīng)常的遇到 ,特別是對(duì)于一個(gè)有繼承關(guān)系的類的時(shí)候,我們需要重寫很多多余的代碼,下面有一種簡(jiǎn)單的方法實(shí)現(xiàn)該功能

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

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、下邊的就是實(shí)現(xiàn)該功能的方法體:

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())) {
            // 調(diào)用source的getter方法和dest的setter方法
            destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
            break;
          }
        }
      }
    } catch (Exception e) {
      throw new Exception("屬性復(fù)制失敗:" + e.getMessage());
    }
  }

3、下邊進(jìn)行測(cè)試:

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、測(cè)試結(jié)果如下:

Java實(shí)現(xiàn)不同的類的屬性之間相互賦值

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

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)億速云的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI