Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics and Method signature

Im trying to create overloading methods in java:

private BasesResponse getResponse(List<ClassA> classA) {
...
}

private BasesResponse getResponse(List<ClassB> classB) {
    ...
}

But eclipse is complaining about: Method getResponse(List<ClassA>) has the same erasure getResponse(List<E>) as another method in type BasisInformationEndpoint.

I thought method signature is method name + parmeter list.... but how can List<ClassA> be the same as List<ClassB>? Doesnt make sense to me.

like image 675
su99-bsa Avatar asked Dec 16 '22 09:12

su99-bsa


2 Answers

Java generic type erasure will make it

private BasesResponse getResponse(List classA) {
...
}

private BasesResponse getResponse(List classB) {
    ...
}

After type erasure it is the same for compiler.

like image 197
Grzegorz Żur Avatar answered Jan 01 '23 18:01

Grzegorz Żur


The generic types (<...>) are present only before compilation stage, to be used for static typing.

Once compiled, those types are "erased" and List<ClassA> essentially becomes List. Thus you can see that when this happens, your two functions become identical.

This is called type erasure, as has been mentioned by the commenter.

like image 41
Karthik T Avatar answered Jan 01 '23 16:01

Karthik T