我的问题可以通过以下代码段总结:
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
使用genet类型未知的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);
}
}
最佳答案
public class A {
private TheClass<Object> instance;
public A(TheClass<Object> instance) {
this.instance = instance;
}
public void do(Object target) {
instance.theMethod(target);
}
}
或者
public class A<T> {
private TheClass<T> instance;
public A(TheClass<T> instance) {
this.instance = instance;
}
public void do(T target) {
instance.theMethod(target);
}
}
关于java - 泛型和正确类型的转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9784779/