/**
* 对象拷贝
*
* @param oldObj
* 原对象
* @param objClass
* 对象类
* @return 新对象
* @throws Exception
* 例外
*/
@SuppressWarnings("unchecked")
public static <T> T copyObjToNew(T oldObj, Class<?> objClass) throws Exception {
if (oldObj == null) {
return null;
}
if (oldObj.getClass() != objClass) {
return null;
}
T newObj = (T) objClass.newInstance();
Field[] fields = oldObj.getClass().getDeclaredFields();
if (fields == null || fields.length == 0) {
return null;
}
for (Field objField : fields) {
objField.setAccessible(true);
String fieldName = objField.getName();
String fieldValue = String.valueOf(objField.get(oldObj));
if (fieldValue == null || "".equals(fieldValue)) {
continue;
}
Field newField = newObj.getClass().getDeclaredField(fieldName);
newField.setAccessible(true);
newField.set(newObj, fieldValue);
}
return (T) newObj;
}
/**
* List对象拷贝
*
* @param oldObjList
* 原List
* @param objClass
* 对象类
* @return 新做成List
* @throws Exception
* 例外
*/
public static <T> List<T> copyObjToNew(List<T> oldObjList, Class<?> objClass) throws Exception {
List<T> listInfo = new ArrayList<T>();
if (oldObjList == null || oldObjList.size() == 0) {
return null;
}
for (T obj : oldObjList) {
T newObj = copyObjToNew(obj, obj.getClass());
if (newObj == null) {
continue;
}else{
listInfo.add(newObj);
}
}
return listInfo;
}
转载于:https://my.oschina.net/u/1858909/blog/482952