测试类
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类中必须有空构造方法。
本文转自IT徐胖子的专栏博客51CTO博客,原文链接http://blog.51cto.com/woshixy/1385523如需转载请自行联系原作者
woshixuye111