好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java实现不同的类的属性之间相互赋值

在开发的时候可能会出现将一个类的属性值,复制给另外一个类的属性值,这在读写数据库的时候,可能会经常的遇到 ,特别是对于一个有继承关系的类的时候,我们需要重写很多多余的代码,下面有一种简单的方法实现该功能

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

查看更多关于Java实现不同的类的属性之间相互赋值的详细内容...

  阅读:13次