java反射(5)通过反射拷贝对象

本篇就是反射的基本应用 

public class CopyObj {

	public static void main(String[] args) throws Exception {
	
		Person p=new Person();
		p.setAddress("北京");
		p.setId(1);
		p.setName("张三丰");
		
		Object obj=copyObject(p);
		System.out.println(obj);

	}
	
	public static Object copyObject(Object obj) throws Exception {
		//获得传递过来对象的方法和属性
		Class<? extends Object> class1 = obj.getClass();
		Field[] fields = class1.getDeclaredFields();
		Constructor<? extends Object>  constructor =class1.getDeclaredConstructor(new Class[] {});
		//创建一个对象
	    Object instance =constructor.newInstance(new Object[] {});
	    for(Field f:fields) {
	    	//获得name
	    	String fname=f.getName();
	    	//获得属性类型
	    	Class<?> type = f.getType();
	    	//获得属性对应的set方法
	    	String setMethodName ="set"+fname.substring(0,1).toUpperCase()+fname.substring(1);
	    	String getMethodName ="get"+fname.substring(0,1).toUpperCase()+fname.substring(1);
	        //获得get方法
	    	Method gmthod =class1.getDeclaredMethod(getMethodName, null);
	    	Object gresult=gmthod.invoke(obj, null);
	    	Method smethod = class1.getDeclaredMethod(setMethodName, new Class[] {gmthod.getReturnType()});		
            smethod.invoke(instance, new Object[] {gresult});  
	    	}
	    return instance;
	}

}

如果对您有帮助 记得帮博主刷个赞或是评论哦

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值