package test.cn;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import test.test1.Person;
public class copy {
public static void main(String[] args) {
Person p = new Person();
p.setAddress("山西大同");
p.setId(1);
p.setName("张三");
Object object = copy(p);
System.out.println(object);
}
/**
* 拷贝方法
*/
public static Object copy(Object obj){
//解析传递过来的对象的属性和构造器
Class<? extends Object> class1 = obj.getClass();
//获取构造器
Constructor<? extends Object> constructor;
Object instance = null;
try {
constructor = class1.getConstructor(new Class[]{});
//创建对象
instance = constructor.newInstance(new Object [] {});
//获取属性
Field[] fields = class1.getDeclaredFields();
for(Field f:fields){
//获取属性的名字
String name = f.getName();
Class<?> type = f.getType();
//创建set方法
String smethod = "set" + name.substring(0,1).toUpperCase() + name.substring(1);
Method setmethod = class1.getDeclaredMethod(smethod, new Class[]{type});
//创建get方法
String gmethod = "get" + name.substring(0,1).toUpperCase() + name.substring(1);
Method getmethod = class1.getDeclaredMethod(gmethod, null);
//获取传递过来类的属性,并且将他的属性值赋值给自己创建的类的对象的属性
Object invoke = getmethod.invoke(obj, null);
Object invoke2 = setmethod.invoke(instance, new Object[]{invoke});
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return instance;
}
}
利用反射拷贝传递过来未知类的对象
最新推荐文章于 2021-12-16 13:26:51 发布