标签:io for ar div sp on new c res
public static Object copy(Object obj) throws Exception{
Class<?> classType = obj.getClass();
// 利用无参构造一个对象
Object copyOj = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
// 获取源对象的属性数组
Field[] fields = classType.getDeclaredFields();
// 遍历数组 进行赋值
for (Field f :fields){
String fieldName = f.getName();
String fristChar = fieldName.substring(0,1).toUpperCase();
String setMethodName ="set"+fristChar+fieldName.substring(1);
String getMethodName = "get"+fristChar+fieldName.substring(1);
Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]{f.getType()});
Method getMethod = classType.getDeclaredMethod(getMethodName, new Class[]{});
Object result = getMethod.invoke(obj);
setMethod.invoke(copyOj, new Object[]{result});
}
return copyOj;
}
利用反射 复制一个对象
标签:io for ar div sp on new c res
原文地址:http://www.cnblogs.com/sunny89/p/3941109.html