target和source之间的转换(目标对象和源对象之间的转换)

本文介绍了一个通用的Java对象转换工具类,支持单个对象及对象列表间的相互转换,并利用Spring的BeanUtils进行属性复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Transfer<Source, Target> {


// 定义两个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;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值