後臺開發中有不少場景須要將數據庫實體,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"}
}
}
複製代碼