The Java™ Tutorials — Generics :Erasure of Generic Methods 泛型方法的类型擦除
原文地址:https://docs.oracle.com/javase/tutorial/java/generics/genMethods.html
关键点
- 消除方法:同对泛型类的处理
- 无限制:替换为Object
- 有限制:替换为第一受限类型
全文翻译
The Java compiler also erases type parameters in generic method arguments. Consider the following generic method:
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;
}
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) { /* ... */ }
_