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

    1. // Counts the number of occurrences of elem in anArray.
    2. //
    3. public static <T> int count(T[] anArray, T elem) {
    4. int cnt = 0;
    5. for (T e : anArray)
    6. if (e.equals(elem))
    7. ++cnt;
    8. return cnt;
    9. }

    由于T是无界的,因此Java编译器将其替换为Object:

    1. public static int count(Object[] anArray, Object elem) {
    2. int cnt = 0;
    3. for (Object e : anArray)
    4. if (e.equals(elem))
    5. ++cnt;
    6. return cnt;
    7. }

    假设定义了以下类:

    1. class Shape { /* ... */ }
    2. class Circle extends Shape { /* ... */ }
    3. class Rectangle extends Shape { /* ... */ }

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

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

    Java编译器替换ŧ为Shape:

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