2018.5.11 Java利用反射实现对象克隆

package com.lanqiao.demo;

/**
 * 创建人
 * @author qichunlin
 *
 */
public class Person {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	//有参构造方法
	public Person(String name,int id) {
		super();
		this.id = id;
		this.name = name;
	}
	
	//无参构造方法
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	
}
package com.lanqiao.demo;
/**
 * 复制对象
 * @author qichunlin
 *
 */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectPerson {
	public Object copy(Object object) throws Exception{
		//加载类
		Class c = object.getClass();
		//获取类中的构造方法
		Constructor ct = c.getConstructor(new Class[] {});
		//在构造方法中传值
		Object obj = ct.newInstance(new Object[] {});
		
		
		//获取所有  属性  返回数组
		Field[] f = c.getDeclaredFields();
		for(Field field : f) {
			String name = field.getName();
			//System.out.println("a"+name);
			//截取
			String firstLetter = name.substring(0, 1).toUpperCase();
			String getMethodName = "get"+firstLetter+name.substring(1);
			String setMethodName = "set"+firstLetter+name.substring(1);
			//获取无参构造方法
			Method getMethod = c.getMethod(getMethodName, new Class[] {});
			Method setMethod = c.getMethod(setMethodName, new Class[] {field.getType()});
			//执行赋值无参构造方法
			Object value = getMethod.invoke(object, new Object[] {});
			System.out.println(value);
			//执行赋值有参构造方法
			setMethod.invoke(obj, new Object[] {value});
		}
		
		return obj;
		
	}
	
}

package com.lanqiao.demo;

import java.lang.reflect.InvocationTargetException;

/**
 * @author qichunlin
 *
 */
public class Test {
	public static void main(String[] args) throws Exception,InvocationTargetException{
		ReflectPerson rp = new ReflectPerson();
		Person p = new Person("Legend",22);
		Person obj = (Person)rp.copy(p);
		System.out.println(obj.getName()+"\t"+obj.getId());
	}
	
}
posted @ 2018-05-11 11:38  LegendQi  阅读(927)  评论(0编辑  收藏  举报