为什么 Java Type Erasure 没有阻止此代码编译

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

我有一个class,其中定义了以下两种方法:

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

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

基于 Java 泛型的类型擦除,此代码不应编译,因为它们都以:

method(Map data)

但是这段代码在Java6时编译成功,在Java8时没有编译成功。

有人可以告诉我为什么它可以在 Java 6 下编译吗?

它在 Java 6 下编译,但在 Java 7 或 Java 8 下不编译。

Java 5 和 Java 6 中存在错误 fixed in Java 7 (#6182950)

该错误页面指的是 JLS, Section 8.4.8.3,其中指出:

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).

这两种方法都没有对方的子签名,因为参数类型 Map<String, Map<String, String>>Map<String, String> 都不是对方的子类型。但是,它们具有相同的擦除,Map.

它永远不应该编译,但是 Java 错误已为 Java 7 修复。