我需要初始化類的泛型型別,但我做不到。就我所做的研究而言,工廠設計模式更好地進行這種泛型型別初始化,但我不知道如何。
這是我的通用服務;
@Service
public abstract class GaService<Entity extends Ga<? extends Play>, DTO extends GaDTO<? extends PlayDTO>> {
@Autowired
protected GaRepository<Entity> repository;
@Autowired
protected Mapper<Entity, DTO> mapper;
public DTO initialize(){
Entity entity = new Entity();
repository.save(entity);
return mapper.toDTO(entity);
}
當您注意到我new Entity()給出了一個錯誤并實作這一點時,我需要找到一種方法來初始化物體。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
我在這里看到兩個選項:
第一個選項:定義要在具體類中實作的抽象工廠方法:
protected abstract Entity newEntity();
第二種選擇:將類傳遞給initialize方法:
public DTO initialize(Class<Entity> entityClass){
Entity entity = entityClass.newInstance();
repository.save(entity);
return mapper.toDTO(entity);
}
UPDATE:第三個選項:傳遞Supplier的initialize方法:
public DTO initialize(Supplier<Entity> newEntity){
Entity entity = newEntity.get();
repository.save(entity);
return mapper.toDTO(entity);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408804.html
標籤:
上一篇:檢查泛型中的地圖資料型別
