在开发的时候可能会出现将一个类的属性值,复制给另外一个类的属性值,这在读写数据库的时候,可能会经常的遇到 ,特别是对于一个有继承关系的类的时候,我们需要重写很多多余的代码,下面有一种简单的方法实现该功能
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;
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/xlgen157387/article/details/47126279
相关文章
猜你喜欢
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 82
-
2025-05-29 50
-
2025-05-29 39
-
2025-05-27 79
-
2025-05-29 101
热门评论


