`
zhengjiong
  • 浏览: 69123 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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

    博客分类:
  • Java
阅读更多

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;
	}
	
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics