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

2025-05-29 0 55

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

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、测试结果如下:

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

可知具有相同属性名和型的属性赋值,剩下的没有被匹配到的结果则为null;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/xlgen157387/article/details/47126279

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java实现不同的类的属性之间相互赋值 https://www.kuaiidc.com/109506.html

相关文章

发表评论
暂无评论