为什么Java Type Erasure不能编译这些代码 [英] Why didn't Java Type Erasure prevents this code from compiling

查看:98
本文介绍了为什么Java Type Erasure不能编译这些代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public Map< String,Map< String,String> >方法(最终Map< String,Map< String,String>>数据)

公共布尔方法(最终Map< String,String>数据)
/ pre>

基于泛型的Java类型擦除,这段代码不应该编译,因为它们都结束了:

 方法(地图数据)

然而,这段代码已成功编译为Java 6,但未在Java 8中编译。



有人可以让我知道为什么它可以在Java 6下编译?

解决方案

它在Java 6下编译,但不在Java 7或Java 8中编译。 Java 5和Java 6中存在一个错误,它在Java 7中修复了(#6182950)



该错误页面引用 JLS,第8.4.8.3节,其中规定:


如果一个类型声明T有一个成员方法m1并且存在一个在T中声明的方法m2或一个超类型为T的方法,那么以下所有都是编译时错误true:


  • m1和m2具有相同的名称。

  • m2可以从T获得。
  • m1的签名不是m2的签名的子签名(§8.4.2)。

    >直接或间接地,m1或某些方法m1覆盖(直接或间接)的签名具有与m2的签名或某些方法m2覆盖(直接或间接)相同的擦除。
  • / b>

这两种方法都没有其他的子签名,因为无论参数类型 Map< String,Map< String,String>> Map< String,String> 是另一个的子类型。但是,它们有相同的擦除, Map



它从来不应该编译,但是Java bug已修复对于Java 7。


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?

解决方案

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.

这篇关于为什么Java Type Erasure不能编译这些代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆