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 泛型类型擦除:何时以及发生什么?


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01