在開發的時候可能會出現將一個類的屬性值,復制給另外一個類的屬性值,這在讀寫數據庫的時候,可能會經常的遇到 ,特別是對于一個有繼承關系的類的時候,我們需要重寫很多多余的代碼,下面有一種簡單的方法實現該功能
1、首先有兩個類,兩個類之間有相同的屬性名和類型,也有不同的屬性名很類型:
1
2
3
4
5
6
7
8
|
public class classtestcopy2 { private int id; private string name; private string password; private string sex; private string age; //get和set方法 } |
1
2
3
4
5
6
|
public class classtestcopy1 { private int id; private string name; private string password; //get和set方法 } |
2、下邊的就是實現該功能的方法體:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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、下邊進行測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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;
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/xlgen157387/article/details/47126279