Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why didn't Java Type Erasure prevents this code from compiling

Tags:

java

generics

I have one class which has the following two methods defined:

public Map<String, Map<String, String>> method(final Map<String, Map<String, String>> data)

public boolean method(final Map<String, String> data)

Based on Java type erasure for generics, this code should not compile because they are all end up with:

method(Map data)

However, this code was successfully compiled in Java 6, but did not compile in Java 8.

Can someone please let me know why it can be compiled under Java 6?

like image 915
Kevin Avatar asked Mar 07 '26 15:03

Kevin


1 Answers

It compiles under Java 6, but not in Java 7 or Java 8.

There was a bug in Java 5 and Java 6 that was fixed in Java 7 (#6182950).

That bug page refers to the JLS, Section 8.4.8.3, which states:

It is a compile-time error if a type declaration T has a member method m1 and there exists a method m2 declared in T or a supertype of T such that all of the following are true:

  • m1 and m2 have the same name.

  • m2 is accessible from T.

  • The signature of m1 is not a subsignature (§8.4.2) of the signature of m2.

  • The signature of m1 or some method m1 overrides (directly or indirectly) has the same erasure as the signature of m2 or some method m2 overrides (directly or indirectly).

Neither method has a subsignature of the other, because neither parameter type, Map<String, Map<String, String>> and Map<String, String> is a subtype of the other. But, they have the same erasure, Map.

It never should have compiled, but that Java bug was fixed for Java 7.

like image 144
rgettman Avatar answered Mar 10 '26 05:03

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!