后台开发中有很多场景需要将数据库实体,Dto,Vo,Param相互转换,有的只是简单的属性拷贝,有的会在这基础上再做写其他的处理,为了避免每次重复开发,使用泛型,开发了一套抽象类抽象共有逻辑
-
AbstractBean
封装泛型类对象,并提供最基本的属性拷贝方法
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); } } } -
AbstractModel/AbstractDto/xxx
基于AbstractBean父类,针对Model和Dto做特殊的泛型限制,并提供模板方法给子类做后续的特殊处理
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"} } }