Spring CrudRepository相同的擦除

huangapple go评论16阅读模式
英文:

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&lt;Person, String&gt; {

    //&lt;S extends T&gt; S save(S entity); //Parent method
    Person save(Person person);//It accepts this 

    //&lt;S extends T&gt; Iterable&lt;S&gt; saveAll(Iterable&lt;S&gt; entities);//Parent method
    Iterable&lt;Person&gt; saveAll(Iterable&lt;Person&gt; persons);//But does not accept this. why can I not use/override this?
    //This Gives error &quot;both methods have same erasure, yet neither overrides the other&quot;
}

答案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 &lt;Object&gt;. 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.

huangapple
  • 本文由 发表于 2020年7月22日 01:04:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63019504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定