使用反射实现类的拷贝

 

public class Customer {

	private Long id;
	private String name;
	private int age;
	
	public Customer(){}

	/**
	 * @return 返回 id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param 对id进行赋值
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return 返回 name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param 对name进行赋值
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return 返回 age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param 对age进行赋值
	 */
	public void setAge(int age) {
		this.age = age;
	}
}

 

 

 

 

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

public class ReflectTester {

	/**
	 * @Title: copy
	 * @Description: 根据指定的方法的参数去 构造一个新的对象的拷贝
	 * @param obj 要拷贝的对象
	 * @return
	 * @author 
	 */
	@SuppressWarnings("rawtypes")
	public Object copy(Object obj) {

		if (null == obj) {
			return null;
		}

		// 获得对象的类型
		Class classType = obj.getClass();

		System.out
				.println("the type of " + obj + " is " + classType.toString());

		Object objectCopy = null;

		try {
			/*
			 * 通过默认构造方法去创建一个新的对象, 
			 * getConstructor的视其参数决定调用哪个构造方法
			 */
			objectCopy = classType.getConstructor(new Class[] {}).newInstance(
					new Object[] {});

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		try {
			// 获得对象的所有属性
			Field[] fields = classType.getDeclaredFields();

			for (Field field : fields) {
				// 属性名称
				String fieldName = field.getName();
				String stringLetter = fieldName.substring(0, 1).toUpperCase();

				// 获得相应属性的getXXX和setXXX方法名称
				String getName = "get".concat(stringLetter).concat(
						fieldName.substring(1));
				String setName = "set".concat(stringLetter).concat(
						fieldName.substring(1));

				// 获取相应的方法
				Method getMethod = classType.getMethod(getName, new Class[] {});
				Method setMethod = classType.getMethod(setName,
						new Class[] { field.getType() });

				// 调用源对象的getXXX()方法
				Object value = getMethod.invoke(obj, new Object[] {});

				// 调用拷贝对象的setXXX()方法
				setMethod.invoke(objectCopy, new Object[] { value });
			}
		} catch (NoSuchMethodException ex) {
			ex.printStackTrace();
		} catch (SecurityException ex) {
			ex.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return objectCopy;
	}
}

 

测试类:

   

public class Test {

	/**
	 * @Title: main
	 * @Description: TODO
	 * @param args
	 * @author wenjianhai
	 */
	public static void main(String[] args) {

		Customer customer = new Customer();
		customer.setAge(20);
		customer.setId(1L);
		customer.setName("test");

		// 拷贝后的新对象
		Customer customer2 = (Customer) new ReflectTester().copy(customer);

		System.out.println("id\tname\tage");

		if (null != customer2) {
			System.out.println(customer2.getId() + "\t" + customer2.getName()
					+ "\t" + customer2.getAge());
		}

		System.out.println("customer=" + customer);
		System.out.println("customer2=" + customer2);
	}

}

 

 

测试结果:

   

the type of com.java.reflect.test1.Customer@d9f9c3 is class com.java.reflect.test1.Customer
id	name	age
1	test	20
customer=com.java.reflect.test1.Customer@d9f9c3
customer2=com.java.reflect.test1.Customer@1a46e30

 

  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值