英文:
Spring CrudRepository same erasure
问题
public interface MyRepository extends CrudRepository<Person, String> {
Person save(Person person);//It accepts this
Iterable<Person> saveAll(Iterable<Person> persons);//But does not accept this. why can I not use/override this?
//This Gives error "both methods have same erasure, yet neither overrides the other"
}
英文:
I have my own custom repository but when I try to override/use CrudRepository it gives me "both methods have same erasure, yet neither overrides the other". Please see below.
public interface MyRepository extends CrudRepository<Person, String> {
//<S extends T> S save(S entity); //Parent method
Person save(Person person);//It accepts this
//<S extends T> Iterable<S> saveAll(Iterable<S> entities);//Parent method
Iterable<Person> saveAll(Iterable<Person> persons);//But does not accept this. why can I not use/override this?
//This Gives error "both methods have same erasure, yet neither overrides the other"
}
答案1
得分: 1
Java的泛型通过擦除(erasure)的概念来实现,意味着在底层,所有的泛型都会被转换成<Object>
。不幸的是,这是Java的一个限制,确保它与Java 5之前编写的代码保持向后兼容,包括泛型。
编译器看到两个具有相同名称和相同参数的方法。
只需将其中一个方法的名称从saveAll
更改为saveAllPeople
或其他任何名称,它就可以工作。
英文:
Java generics work through the concept known as erasure, meaning that under the hood all generics get transformed into <Object>
. This unfortunately is one of the limitations of Java making sure it is backwards compatible with code written before Java 5 and generics.
Compiler sees both methods with identical names and identical parameters.
Just change the name of one of the methods from saveAll
to saveAllPeople
or whatever and it will work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论