我有這本書的代碼在Java思考,其中布魯斯表示調用方法設置()的警告。代碼如下:
通用類型擦除警告
package testPackage;
class GenericBase<T> {
private T element;
public void set(T arg) { arg = element; }
public T get() { return element; }
}
class Derived1<T> extends GenericBase<T> {}
class Derived2 extends GenericBase {} // No warning
// class Derived3 extends GenericBase<?> {}
// Strange error:
// unexpected type found : ?
// required: class or interface without bounds
public class ErasureAndInheritance {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Derived2 d2 = new Derived2();
Object obj = d2.get();
d2.set(obj); // Warning here!
}
}
如果我刪除了註釋,我得到以下警告:
類型安全:該方法集(對象)屬於原始類型GenericBase。參考泛型GenericBase應參數化
我的問題是,爲什麼在set()方法上顯示警告?有人可以解釋這個警告的含義嗎?
順便說一句,我對Java泛型是全新的,雖然我讀了其他關於泛型的問題,但我仍然對Erasure感到困惑。
Erasure =>在編譯過程之後,代碼不知道有關泛型的任何信息 – 2014-08-27 14:39:15
@MarcoAcierno那麼,我明白,但我的混淆來自混合原始和參數化類型。 – 2014-08-27 14:41:55