泛型的擦除

Java SE5中加入了泛型。为了不破坏现有的类库,将泛型融入Java,Java用到了擦除。

看看下面一个例子:

class Erased<T>{
 private final int SIZE=100;
 public  void f(Object arg){
  if(arg instanceof T){}
  T var = new T();
  T[] array=new T[SIZE];
 }
}

 

我们会认为这里没有什么错误,然而结果是编译错误:

Cannot perform instanceof check against type parameter T. Use instead its erasure Object since generic type information will be erased at runtime

也就是说,在运行时,T类型会被擦除。

你可能感兴趣的:(java,object,Class)