- new T() 無法實現(xiàn)羔味,因為擦除买优,還因為不確定T有無參構(gòu)造函數(shù);
package chapter15._8;
public class Erased<T> {
private final int SIZE = 100;
public static void f(Object arg) {
// if (arg instanceof T) {} // error
// T var = new T(); // error
// T[] array = new T[SIZE]; // error
// T[] array = (T)new Object[SIZE]; // error
}
}
package chapter15._8;
class Building {}
class House extends Building {}
public class ClassTypeCapture<T> {
// 類型標(biāo)簽
Class<T> kind;
public ClassTypeCapture(Class<T> kind) {
this.kind = kind;
}
public boolean f(Object arg) {
// 如果arg可以轉(zhuǎn)型成kind,返回true
return kind.isInstance(arg);
}
public static void main(String[] args) {
ClassTypeCapture<Building> ctt1 = new ClassTypeCapture<Building>(Building.class);
System.out.println(ctt1.f(new Building()));
System.out.println(ctt1.f(new House()));
ClassTypeCapture<House> ctt2 = new ClassTypeCapture<House>(House.class);
System.out.println(ctt2.f(new Building()));
System.out.println(ctt2.f(new House()));
}
}
輸出
true
true
false
true