Java實現(xiàn)不同的類的屬性之間相互賦值
更新時間:2019年03月27日 09:41:13 作者:徐劉根
今天小編就為大家分享一篇關于Java實現(xiàn)不同的類的屬性之間相互賦值,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
在開發(fā)的時候可能會出現(xiàn)將一個類的屬性值,復制給另外一個類的屬性值,這在讀寫數(shù)據(jù)庫的時候,可能會經常的遇到 ,特別是對于一個有繼承關系的類的時候,我們需要重寫很多多余的代碼,下面有一種簡單的方法實現(xiàn)該功能
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、下邊的就是實現(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())) {
// 調用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;
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
maven繼承父工程統(tǒng)一版本號的實現(xiàn)
這篇文章主要介紹了maven繼承父工程統(tǒng)一版本號的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08

