Documentation

The Java™ Tutorials
Hide TOC
Erasure of Generic Methods泛型方法的擦除
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Type Erasure

Erasure of Generic Methods泛型方法的擦除

The Java compiler also erases type parameters in generic method arguments. Java编译器还删除泛型方法参数中的类型参数。Consider the following generic method:考虑下面的泛型方法:

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

Because T is unbounded, the Java compiler replaces it with Object:因为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;
}

Suppose the following classes are defined:假设定义了以下类:

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

You can write a generic method to draw different shapes:您可以编写通用方法来绘制不同的形状:

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

The Java compiler replaces T with Shape:Java编译器将T替换为Shape

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

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