Java反射学习-5 - 反射复制对象

通过反射方式复制对象:

 1 package cn.tx.reflect;
 2 
 3 import java.lang.reflect.Constructor;
 4 import java.lang.reflect.Field;
 5 import java.lang.reflect.Method;
 6 
 7 /**
 8  * 反射复制对象
 9  * @author Administrator
10  *
11  */
12 public class ReflectLearn5 {
13 
14     public static void main(String[] args) throws Exception {
15         Person p = new Person(3,"jack","america");
16         Object obj = copyOjbect(p);
17         System.out.println(obj);
18     }
19     
20     public static Object copyOjbect(Object obj) throws Exception{
21         //获得传递过来的对象的属性和构造器
22         Class<? extends Object> class1 = obj.getClass();
23         Field[] fields = class1.getDeclaredFields();
24         Constructor constructor = class1.getConstructor();
25         Object instance = constructor.newInstance(null);
26         for (Field f : fields) {
27             //获得属性名字
28             String name = f.getName();
29             //获得属性类型
30             Class<?> type = f.getType();
31             //获得属性对应的set方法
32             String setMethodName = "set"+ name.substring(0,1).toUpperCase()+name.substring(1);
33             String getMethodName = "get"+ name.substring(0,1).toUpperCase()+name.substring(1);
34             //获得get方法
35             Method gmethod = class1.getDeclaredMethod(getMethodName, null);
36             //调用get方法获得被复制对象的一个属性值
37             Object gresult = gmethod.invoke(obj, null);
38             //get方法的参数类型是string,返回值类型也是
39             Method smethod = class1.getDeclaredMethod(setMethodName,type);
40 //            Method smethod = class1.getDeclaredMethod(setMethodName,gmethod.getReturnType());
41             smethod.invoke(instance, gresult);
42             
43         }
44         return instance;
45     }
46 }

结果:

 

转载于:https://www.cnblogs.com/enjoyjava/p/9135579.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值