后台开发中有不少场景须要将数据库实体,Dto,Vo,Param相互转换,有的只是简单的属性拷贝,有的会在这基础上再作写其余的处理,为了不每次重复开发,使用泛型,开发了一套抽象类抽象共有逻辑数据库
封装泛型类对象,并提供最基本的属性拷贝方法bash
class AbstractBean<T> {
/**
* 当前泛型真实类型的Class
*/
private Class<T> modelClass;
AbstractBean() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
}
T toOtherBean(){
try {
T model = modelClass.newInstance();
BeanUtils.copyProperties(this,model);
return model;
} catch (ReflectiveOperationException e) {
throw new ServiceException(ResultCode.FAIL,e);
}
}
}
复制代码
基于AbstractBean父类,针对Model和Dto作特殊的泛型限制,并提供模板方法给子类作后续的特殊处理ui
public abstract class AbstractParam<T extends AbstractDto> extends AbstractBean<T> {
public T toDto(){
return super.toOtherBean();
}
}
复制代码
public abstract class AbstractDto<T extends IModel> extends AbstractBean<T> {
public T toModel(){
return super.toOtherBean();
}
public T toModel(Consumer<T> consumer){
T t = super.toOtherBean();
consumer.accept(t);
return t;
}
}
复制代码
@Data
public class CustomModel implements AbstractModel {
private Integer id;
private String name;
private String idConcatName;
}
复制代码
@Data
public class CustomDto extends AbstractDto<CustomModel> {
private Integer id;
private String name;
}
复制代码
@Data
public class CustomParam extends AbstractParam<CustomDto> {
private Integer id;
private String name;
}
复制代码
public class Test{
public static void main(String[] args) {
CustomParam customParam = new CustomParam();
customParam.setId(1);
customParam.setName("gwf");
CustomDto customDto = customParam.toDto();
System.out.println(JSON.toJSONString(customDto)); // 输出 {"id":1,"name":"gwf"}
CustomModel iModel = customDto.toModel(model -> model.setIdConcatName(model.getId()+":"+model.getName()));
System.out.println(JSON.toJSONString(iModel)); // 输出 {"id":1,"idConcatName":"1:gwf","name":"gwf"}
}
}
复制代码