Generic 使用的限制 #
-
原生数据类型不能用到 Type 参数中。写 Pair<double> 会出错,而应使用 Pair<Double>。
-
运行时类型检测只对 Raw Type 起作用。
if (a instanceof Pair<String>)与下面的写法是完全一样的:
if (a instanceof Pair<T>)Type 参数会被忽略,另一种写法是:
if (stringPair.getClass() == employeePair.getClass()) -
Throw 和 Catch 语句中不能使用 Generic 类型。
public class Problem<T> extends Exception { /* . . . */ } // ERROR--can't extend Throwable -
数组中不能使用 Type 参数。
Pair<String>[] table = new Pair<String>[10]; // ERROR -
Type 变量不能实例化。
public Pair() { first = new T(); second = new T(); } // ERROR必须通过反射才能创建 Type 对应的实例。参看 Core Java I 8th 第628页。
...