我的问题可以概括式的这个片段:泛型和铸造到正确的类型
public interface TheClass<T> {
public void theMethod(T obj);
}
public class A {
private TheClass<?> instance;
public A(TheClass<?> instance) {
this.instance = instance;
}
public void doWork(Object target) {
instance.theMethod(target); // Won't compile!
// However, I know that the target can be passed to the
// method safely because its type matches.
}
}
我A
类使用的TheClass
一个实例,其泛型类型不明。它具有一个方法,目标传递为Object
,因为TheClass
实例可以用任何类进行参数化。但是,编译器不会让我像这样传递目标,这是正常的。
我该怎么办才能绕过这个问题?
脏的解决方案是声明实例为TheClass<? super Object>
,它工作正常,但在语义上是错误的...
另一种解决方案我使用之前是声明实例为原料的类型,只是TheClass
,但它是坏的练习,所以我想纠正我的错误。
解
public class A {
private TheClass<Object> instance; // type enforced here
public A(TheClass<?> instance) {
this.instance = (TheClass<Object>) instance; // cast works fine
}
public void doWork(Object target) {
instance.theMethod(target);
}
}
你为什么不还键入'A'? – 2012-03-20 10:15:45
+1,一个很好的问题!等待答案...... – aProgrammer 2012-03-20 10:17:38
A是我制作的开源库的一部分,许多人都使用它,而打字A意味着强大的api突破。最近我发现了这个问题,因为之前我使用原始类型为“TheClass”实例,因为我不知道这是一个糟糕的概念。它工作得很好,但被认为是不好的做法,所以我想纠正这种误用。 – 2012-03-20 10:19:06