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 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01