Java generics type erasure: when and what happens?(Java 泛型类型擦除:何时以及发生什么?)
问题描述
I read about Java's type erasure on Oracle's website.
When does type erasure occur? At compile time or runtime? When the class is loaded? When the class is instantiated?
A lot of sites (including the official tutorial mentioned above) say type erasure occurs at compile time. If the type information is completely removed at compile time, how does the JDK check type compatibility when a method using generics is invoked with no type information or wrong type information?
Consider the following example: Say class A
has a method, empty(Box<? extends Number> b)
. We compile A.java
and get the class file A.class
.
public class A {
public static void empty(Box<? extends Number> b) {}
}
public class Box<T> {}
Now we create another class B
which invokes the method empty
with a non-parameterized argument (raw type): empty(new Box())
. If we compile B.java
with A.class
in the classpath, javac is smart enough to raise a warning. So A.class
has some type information stored in it.
public class B {
public static void invoke() {
// java: unchecked method invocation:
// method empty in class A is applied to given types
// required: Box<? extends java.lang.Number>
// found: Box
// java: unchecked conversion
// required: Box<? extends java.lang.Number>
// found: Box
A.empty(new Box());
}
}
My guess would be that type erasure occurs when the class is loaded, but it is just a guess. So when does it happen?
Type erasure applies to the use of generics. There's definitely metadata in the class file to say whether or not a method/type is generic, and what the constraints are etc. But when generics are used, they're converted into compile-time checks and execution-time casts. So this code:
List<String> list = new ArrayList<String>();
list.add("Hi");
String x = list.get(0);
is compiled into
List list = new ArrayList();
list.add("Hi");
String x = (String) list.get(0);
At execution time there's no way of finding out that T=String
for the list object - that information is gone.
... but the List<T>
interface itself still advertises itself as being generic.
EDIT: Just to clarify, the compiler does retain the information about the variable being a List<String>
- but you still can't find out that T=String
for the list object itself.
这篇关于Java 泛型类型擦除:何时以及发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 泛型类型擦除:何时以及发生什么?
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01