target和source之間的轉換(目標對象和源對象之間的轉換)

public class Transfer {


// 定義兩個Class對象
private Class sourceClazz;
private Class targetClazz;


public Transfer() {
Type[] c = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
sourceClazz = (Class) c[0];
targetClazz = (Class) c[1];
}


// 源文件和目標文件之間的轉換
protected void convertExt(Source source, Target target) {
}


protected void reverseConvertExt(Target target, Source source) {
};
// 將目標文件List集合轉爲源文件list集合


public List<Source> reverseConvert(List<Target> targetList) {
// 首先判斷目標list集合是否爲空,如果爲空則返回null
if (CollectionUtils.isEmpty(targetList)) {
return null;
}
// 創建源文件list集合
List<Source> sourceList = new ArrayList<>(targetList.size());
for (Target target : targetList) {
Source source = null;
try {
source = (Source) sourceClazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
BeanUtils.copyProperties(target, source);
reverseConvertExt(target, source);
sourceList.add(source);
}
return sourceList;
}


// 將源文件List集合轉爲目標文件list集合
public List<Target> convert(List<Source> sourceList) {
// 判斷源文件是否爲空
if (CollectionUtils.isEmpty(sourceList)) {
return null;
}
List<Target> targetList = new ArrayList<>(sourceList.size());
for (Source source : sourceList) {
Target target = null;
try {
target = (Target) targetClazz.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BeanUtils.copyProperties(source, target);
convertExt(source, target);
targetList.add(target);
}
return targetList;
}


// 將源文件轉爲目標文件
public Target convert(Source source) {
// 判斷源文件是否爲空
if (source == null) {
return null;
}
Target target = null;
try {
target = (Target) targetClazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
BeanUtils.copyProperties(source, target);
convertExt(source, target);
return target;
}


// 將目標文件反轉爲源文件
public Source reverseConvert(Target target) {
if (target == null) {
return null;
}
Source source = null;
try {
source = (Source) sourceClazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
BeanUtils.copyProperties(target, source);
reverseConvertExt(target, source);
return source;
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章