[英]Method not applicable for arguments with generics
我不是泛型專家,並且在嘗試對某些類進行重新設計以避免代碼重復時,我在強迫自己使用泛型,以便盡可能地做到最好。
我在標記的行中遇到下一個錯誤:
類型CrudRepository中的delete(Long)方法不適用於自變量(捕獲的#5-?擴展KeyProfileEntity)
這是我的課:
public abstract class KeyProfileService {
protected CrudRepository<? extends KeyProfileEntity, Long> myRepository;
public List<KeyProfileEntity> getList() {
List<KeyProfileEntity> result = new ArrayList<>();
this.myRepository.findAll().forEach(result::add);
return result;
}
public KeyProfileEntity create(KeyProfileEntity entity) {
return this.myRepository.save(entity); //error
}
public boolean delete(long id) {
if (this.myRepository.exists(id)) {
this.myRepository.delete(this.myRepository.findOne(id));//error
return true;
}
return false;
}
public void update(KeyProfileEntity entity) {
this.myRepository.save(entity); //error
}
public KeyProfileEntity getEmployee(long id) throws NotFoundEntryException {
if (this.myRepository.exists(id))
return this.myRepository.findOne(id);
throw new NotFoundEntryException();
}
}
我認為這是你們需要的所有信息,否則請發表評論,我會附加更多內容。
提前致謝!
您可以通過刪除<? extends ...>
來修復它<? extends ...>
從myRepository
<? extends ...>
綁定通配符:
protected CrudRepository<KeyProfileEntity, Long> myRepository;
據我KeyProfileEntity
,即使使用KeyProfileEntity
子類,您的類仍然可以使用:
KeyProfileService service = new KeyProfileServiceImpl();
service.update(new ChildKeyProfileEntity());
只有一個限制: getList()
將始終返回List<KeyProfileEntity>
,而不返回List<ChildKeyProfileEntity>
。
或者,可以使KeyProfileService
通用,並確保使用綁定的已知子類型:
public abstract class KeyProfileService<K extends KeyProfileEntity> {
protected CrudRepository<K, Long> myRepository;
public List<K> getList() { // using K
List<K> result = new ArrayList<>(); // here too
this.myRepository.findAll().forEach(result::add);
return result;
}
public K create(K entity) { // using K
return this.myRepository.save(entity);
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.