java 反射拷贝_Java中利用反射原理拷贝对象

测试类

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.Date;

public class Test

{

/**

* 拷贝对象方法

*/

public static Object copy(Object objSource)

throws IllegalArgumentException, SecurityException, InstantiationException,

IllegalAccessException, InvocationTargetException,NoSuchMethodException

{

// 获取源对象类型

Class> clazz = objSource.getClass();

// 获取源对象构造函数

Constructor> construtctor = clazz.getConstructor();

// 实例化出目标对象

Object objDes = construtctor.newInstance();

// 获得源对象所有属性

Field[] fields = clazz.getDeclaredFields();

// 遍历所有属性

for (int i = 0; i < fields.length; i++)

{

// 属性对象

Field field = fields[i];

// 属性名

String fieldName = field.getName();

// 获取属性首字母

String firstLetter = fieldName.substring(0, 1).toUpperCase();

// 拼接get方法名如getName

String getMethodName = "get" + firstLetter + fieldName.substring(1);

// 得到get方法对象

Method getMethod = clazz.getMethod(getMethodName);

// 对源对象调用get方法获取属性值

Object value = getMethod.invoke(objSource);

// 拼接set方法名

String setMethodName = "set" + firstLetter + fieldName.substring(1);

// 获取set方法对象

Method setMethod = clazz.getMethod(setMethodName, new Class[] { field.getType() });

// 对目标对象调用set方法装入属性值

setMethod.invoke(objDes, new Object[] { value });

}

return objDes;

}

public static void main(String[] args)

throws IllegalArgumentException, SecurityException,InstantiationException,                                        IllegalAccessException,InvocationTargetException, NoSuchMethodException

{

// 学生源对象

Student studentSource = new Student();

studentSource.setNum(1);

studentSource.setName("xy");

studentSource.setBirthDay(new Date());

// 复制学生对象

Student studentDes = (Student) copy(studentSource);

System.out.println(studentDes.getName());

}

}

实体类

public class Student

{

private int num;

private String name;

private Date birthDay;

public Student()

{

super();

}

public Student(int num, String name, Date birthDay)

{

super();

this.num = num;

this.name = name;

this.birthDay = birthDay;

}

public int getNum()

{

return num;

}

public void setNum(int num)

{

this.num = num;

}

public String getName()

{

return name;

}

public void setName(String name)

{

this.name = name;

}

public Date getBirthDay()

{

return birthDay;

}

public void setBirthDay(Date birthDay)

{

this.birthDay = birthDay;

}

}

注意因为在copy方法中调用的newInstance是不带参数的,所以student类中必须有空构造方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值