反射练习-用反射实现拷贝对象

package com.zj.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 功能:用反射实现拷贝对象
 * @author zhengjiong
 * time:2011-9-17 19:37:46
 */
public class ReflectTest4
{
	public static void main(String[] args) throws Exception
	{
		ReflectTest4 rf = new ReflectTest4();
		
		People p1 = new People("zhangsn", 15);
		
		//执行拷贝
		People p2 = (People)rf.copy(p1);
		
		System.out.println(p2.getName() + " , " + p2.getAge());
	}

	private Object copy(Object p1) throws Exception
	{
		Class<?> classType = p1.getClass();
		//获得所有属性
		Field[] fields = classType.getDeclaredFields();
		
		//获得People的实例
		Object p2 = classType.newInstance();
		
		for(int i = 0; i < fields.length; i++){
			String methodName = fields[i].getName();
			String firstLetter = methodName.substring(0, 1).toUpperCase();
			
			//获得set,get方法名
			String getMethodName = "get" + firstLetter + methodName.substring(1);
			String setMethodName = "set" + firstLetter + methodName.substring(1);
			
			//获得People类每个属性的set,get方法
			Method getMethod = classType.getMethod(getMethodName, new Class<?>[]{});
			Method setMethod = classType.getMethod(setMethodName, new Class<?>[]{fields[i].getType()});
			
			//调用p1对象的get方法获得值
			Object value = getMethod.invoke(p1, new Object[]{});
			//把获得的值传给p2的set方法
			setMethod.invoke(p2, new Object[]{value});
		}
		
		return p2;
	}
}

class People{
	private String name;
	private int age;
	
	public People(){}
	
	public People(String name, int age){
		this.name = name;
		this.age = age;
	}
	
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值