利用反射克隆一个对象

package com.softeem.example;

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

import com.softeem.dto.User;

public class ObjectClone {

	/**
	 * 根据提供的参数拷贝一个数据一致的对象
	 * @param target
	 * @return
	 */
	public static Object copy(Object source){
		//获取指定对象的Class对象
		Class clz = source.getClass();
		Object newObj = null;
		try {
			//根据class对象创建当前类型的实例(空对象)
			newObj = clz.newInstance();
			//获取当前类中包含的所有属性
			Field[] fields = clz.getDeclaredFields();
			for (Field field : fields) {
				//拼接获取setter/getter方法的名称
				String setMethodName = "set"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);
				String getMethodName = "get"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);
				//根据方法名称获取方法对象
				Method method_set = clz.getMethod(setMethodName, field.getType());//setter方法
				Method method_get = clz.getMethod(getMethodName);//getter方法
			
				//执行源对象指定属性的getter方法,获取属性值
				Object returnval = method_get.invoke(source);
				//执行新对象的setter方法,将源对象的属性值设置给新对象
				method_set.invoke(newObj, returnval);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return newObj;
	}	
	
	public static void main(String[] args) {
//		Student s = new Student(1,"孙悟空","男",18,"打铁");
//		Object obj = ObjectClone.copy(s);
//		System.out.println(obj);
		
		User user = new User();
		user.setId(1);
		user.setUsername("softeem");
		user.setPassword("123456");
		Object obj = ObjectClone.copy(user);
		System.out.println(obj);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值