【The Java? Tutorials】【Generics】8. Type Erasure

泛型信息只存在于代碼編譯階段,在進(jìn)入 JVM 之前,與泛型相關(guān)的信息會被擦除掉。

引入泛型的目的:
Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming.

為了實現(xiàn)泛型,Java編譯器進(jìn)行了在編譯的時候會進(jìn)行類型擦除:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

Erasure of Generic Types

unbound

public class Node<T> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}

類型擦除之后:

public class Node {

    private Object data;
    private Node next;

    public Node(Object data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Object getData() { return data; }
    // ...
}

bound

public class Node<T extends Comparable<T>> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}

類型擦除之后:

public class Node {

    private Comparable data;
    private Node next;

    public Node(Comparable data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Comparable getData() { return data; }
    // ...
}

注意經(jīng)過類型擦除之后,Node<T>變?yōu)镹ode,Comparable<T>變?yōu)镃omparable。

Erasure of Generic Methods

unbound

// Counts the number of occurrences of elem in anArray.
//
public static <T> int count(T[] anArray, T elem) {
    int cnt = 0;
    for (T e : anArray)
        if (e.equals(elem))
            ++cnt;
        return cnt;
}

類型擦除之后:

public static int count(Object[] anArray, Object elem) {
    int cnt = 0;
    for (Object e : anArray)
        if (e.equals(elem))
            ++cnt;
        return cnt;
}

bound

假設(shè)有如下類定義:

class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }
public static <T extends Shape> void draw(T shape) { /* ... */ }

類型擦除之后變?yōu)椋?/p>

public static void draw(Shape shape) { /* ... */ }

Effects of Type Erasure and Bridge Methods

類型擦除可能會導(dǎo)致一些你沒有預(yù)料到的情況,比如下面這個例子:

有下面兩個類:

public class Node<T> {

    public T data;

    public Node(T data) { this.data = data; }

    public void setData(T data) {
        System.out.println("Node.setData");
        this.data = data;
    }
}

public class MyNode extends Node<Integer> {
    public MyNode(Integer data) { super(data); }

    public void setData(Integer data) {
        System.out.println("MyNode.setData");
        super.setData(data);
    }
}

下面這段代碼:

MyNode mn = new MyNode(5);
Node n = mn;            // A raw type - compiler throws an unchecked warning
n.setData("Hello");     
Integer x = mn.data;    // Causes a ClassCastException to be thrown.

經(jīng)過類型擦除之后會變?yōu)椋?/p>

MyNode mn = new MyNode(5);
Node n = (MyNode)mn;         // A raw type - compiler throws an unchecked warning
n.setData("Hello");
Integer x = (String)mn.data; // Causes a ClassCastException to be thrown.

這段代碼編譯的時候并不會報錯,但是這顯然不合理。因為我們傳進(jìn)去一個String,但是在mn看來,里面存的是一個Integer。我們運行的時候會出現(xiàn)如下錯誤:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at Test.main(Test.java:10)

需要注意的是,是n.setData("Hello")拋出了ClassCastException異常,這是為什么呢?n.setData("Hello")調(diào)用的不是Node中的setData(Object data)嗎?

Bridge Methods

When compiling a class or interface that extends a parameterized class or implements a parameterized interface, the compiler may need to create a synthetic method, called a bridge method, as part of the type erasure process.

在類型擦除之后,Node中的方法變?yōu)閟etData(Object data),而MyNode中的方法setData(Integer data),這兩個方法的簽名是不一樣的,即MyNode中的setData不是對Node的setData的重寫。

為了保留類型擦除之后的多態(tài)性,Java編譯器會自動生成一個bridge method,使得子類的行為符合預(yù)期,如下所示:

class MyNode extends Node {

    // Bridge method generated by the compiler
    //
    public void setData(Object data) {
        setData((Integer) data);
    }

    public void setData(Integer data) {
        System.out.println("MyNode.setData");
        super.setData(data);
    }

    // ...
}

這就可以理解上面的代碼為什么編譯的時候不會報錯,而執(zhí)行的時候會拋出異常了(相當(dāng)于執(zhí)行了以下代碼)。

Integer i = (Integer)(Object) "Hello";

Restrictions on Generics

Cannot Instantiate Generic Types with Primitive Types

Pair<int, char> p = new Pair<>(8, 'a');  // compile-time error

可以用Java的自動裝箱修改以上代碼:

Pair<Integer, Character> p = new Pair<>(8, 'a');

Cannot Create Instances of Type Parameters

public static <E> void append(List<E> list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}

這是很好理解的,因為你根本不知道E有哪些構(gòu)造函數(shù),有些類是沒有不帶參數(shù)的構(gòu)造函數(shù)的,new E()不知道具體調(diào)用哪個構(gòu)造函數(shù)。

可以利用反射繞過上面的問題:

public static <E> void append(List<E> list, Class<E> cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}

這樣我們就可以像下面這樣調(diào)用append方法:

List<String> ls = new ArrayList<>();
append(ls, String.class);

Cannot Declare Static Fields Whose Types are Type Parameters

A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed.
假設(shè)是允許的,就會在語義上出現(xiàn)混亂:

public class MobileDevice<T> {
    private static T os;

    // ...
}
MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();

因為os是被phone、pager和pc共享的,那現(xiàn)在os的具體類型是什么呢?

Cannot Use Casts or instanceof with Parameterized Types

Because the Java compiler erases all type parameters in generic code, you cannot verify which parameterized type for a generic type is being used at runtime:

public static <E> void rtti(List<E> list) {
    if (list instanceof ArrayList<Integer>) {  // compile-time error
        // ...
    }
}

運行的時候并沒有跟蹤類型參數(shù),所以并不能區(qū)分ArrayList<Integer>和ArrayList<String>。我們能做的,最多是用unbounded wildcard來區(qū)分一個list是不是ArrayList:

public static void rtti(List<?> list) {
    if (list instanceof ArrayList<?>) {  // OK; instanceof requires a reifiable type
        // ...
    }
}

特別的,你不能強制轉(zhuǎn)換為參數(shù)化的類型(除非是unbounded wildcards):

List<Integer> li = new ArrayList<>();
List<Number>  ln = (List<Number>) li;  // compile-time error

但是像下面這種情況是可以強制轉(zhuǎn)換的:

List<String> l1 = ...;
ArrayList<String> l2 = (ArrayList<String>)l1;  // OK

Cannot Create Arrays of Parameterized Types

List<Integer>[] arrayOfLists = new List<Integer>[2];  // compile-time error

我們先來看一段非泛型代碼:

Object[] strings = new String[2];
strings[0] = "hi";   // OK
strings[1] = 100;    // An ArrayStoreException is thrown.

我們假設(shè)是能創(chuàng)建泛型數(shù)組的,我們用泛型數(shù)組做一樣的事:

Object[] stringLists = new List<String>[];  // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList<String>();   // OK
stringLists[1] = new ArrayList<Integer>();  // An ArrayStoreException should be thrown, but the runtime can't detect it.

如果可以創(chuàng)建泛型數(shù)組,上面的代碼就會如法拋出ArrayStoreException異常。

Cannot Create, Catch, or Throw Objects of Parameterized Types

泛型類不能直接或間接繼承Throwable:

// Extends Throwable indirectly
class MathException<T> extends Exception { /* ... */ }    // compile-time error

// Extends Throwable directly
class QueueFullException<T> extends Throwable { /* ... */ // compile-time error

不能捕獲類型參數(shù)實例:

public static <T extends Exception, J> void execute(List<J> jobs) {
    try {
        for (J job : jobs)
            // ...
    } catch (T e) {   // compile-time error
        // ...
    }
}

但是可以在throws語句中使用類型參數(shù):

class Parser<T extends Exception> {
    public void parse(File file) throws T {     // OK
        // ...
    }
}

Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type

A class cannot have two overloaded methods that will have the same signature after type erasure.
所以下面的代碼會出現(xiàn)編譯錯誤:

public class Example {
    public void print(Set<String> strSet) { }
    public void print(Set<Integer> intSet) { }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Chapter 5 Generics 范型 SINCE Java 5, generics have been a ...
    LaMole閱讀 1,120評論 3 1
  • "Unterminated string literal.": "未終止的字符串文本。", "Identifier...
    兩個心閱讀 8,550評論 0 4
  • { "Unterminated string literal.": "未終止的字符串文本。", "Identifi...
    Elbert_Z閱讀 10,990評論 0 2
  • 天覆地載,乾坤定矣;男尊女卑,家室成矣;一陰一陽,道之體也;一男一女,家之本也;陰陽失衡,天災(zāi)生也;男女失配,蕭墻...
    白露丹楓閱讀 442評論 0 0
  • 這幾日,身邊的人紛紛被兩部劇圈粉,無論是大唐農(nóng)藥,還是三生三世,都是把人虐的不要不要的 依我看來,那些虐心的點無非...
    見說世間離別苦閱讀 386評論 0 1

友情鏈接更多精彩內(nèi)容