文档

Java™ 教程-Java Tutorials 中文版
泛型方法的擦除
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Type Erasure

泛型方法的擦除

Java 编译器还会擦除泛型方法参数中的类型形参。请考虑以下泛型方法:

// 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;
}

因为 T 是无界的,所以 Java 编译器将其替换为 Object

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

假设定义了以下类:

class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }

你可以编写一个泛型方法来绘制不同的形状:

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

Java 编译器用 Shape 替换 T

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

Previous page: Erasure of Generic Types
Next page: Effects of Type Erasure and Bridge Methods