Java 泛型类型擦除:何时以及发生什么?

2022-01-30 00:00:00 java generics type-erasure

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.

相关文章