/** * 對象拷貝 * * @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; }