[java]代码库
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
public Object copy(Object obj) throws Exception {
//得到要复制对象的类型
Class calssType = obj.getClass();
//创建一个实例
Object objCopy = calssType.getConstructor(new Class[] {}).newInstance(new Class[] {});
//获取声明的方法
Field[] fields = calssType.getDeclaredFields();
//遍历字段
for (Field f : fields) {
//获取字段名
String fieldName = f.getName();
//生成get和set方法
String midLetter = fieldName.substring(0, 1).toUpperCase();
Method getMethod = calssType.getMethod("get" + midLetter + fieldName.substring(1), new Class[] {});
Method setMethod = calssType.getMethod("set" + midLetter + fieldName.substring(1), new Class[] { f.getType() });
//调用get和set方法
Object value = getMethod.invoke(obj, new Object[] {});
setMethod.invoke(objCopy, new Object[] { value });
}
//返回对象
return objCopy;
}
public static void main(String[] args) throws Exception {
Customer c = new Customer();
c.setUserName("qinying");
c.setAge(27);
//复制一个新的对象
Customer c2 = (Customer) new Test().copy(c);
System.out.println(c2.getUserName());
System.out.println(c2.getAge());
}
}
class Customer {
public Customer() {
}
private String userName;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
//源代码片段来自云代码http://yuncode.net