import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test06 {
public static void main(String[] args) throws Exception {
Person person = new Person();
person.setName("张三");
person.setGender("男");
person.setId(1);
Object o = copyObject(person);
System.out.println(o);
}
public static Object copyObject(Object obj) throws Exception {
// 获得传递过来的对象的方法的属性和构造器
Class<?> class1 = obj.getClass();
Field[] fields = class1.getDeclaredFields();
Constructor<?> constructors = class1.getConstructor();
// 创建一个对象
Object instance = constructors.newInstance(new Object[]{});
for (Field f : fields) {
// 获得属性的name
String name = f.getName();
// 获得属性的类型
Class<?> type = f.getType();
// 获得属性对应的set的方法
String setMethodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
String getMethodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
// 获得get方法
Method gMethod = class1.getDeclaredMethod(getMethodName, null);
// 调用get方法获得被拷贝的对象的一个属性值
Object invoke = gMethod.invoke(obj, null);
// 获得set方法
Method sMethod = class1.getDeclaredMethod(setMethodName, new Class[]{gMethod.getReturnType()});
sMethod.invoke(instance, new Object[]{invoke});
}
return instance;
}
}