我的问题可以通过这个片段总结出来:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
我的类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);
}
}
Run Code Online (Sandbox Code Playgroud)
public class A {
private TheClass<Object> instance;
public A(TheClass<Object> instance) {
this.instance = instance;
}
public void do(Object target) {
instance.theMethod(target);
}
}
Run Code Online (Sandbox Code Playgroud)
或者
public class A<T> {
private TheClass<T> instance;
public A(TheClass<T> instance) {
this.instance = instance;
}
public void do(T target) {
instance.theMethod(target);
}
}
Run Code Online (Sandbox Code Playgroud)