我在代码中使用了策略模式,这是一个简短的片段:
public interface FindingStrategy<T> {
Callable<T> setAction();
}
class FindSomething implements BindingActionStrategy {
...
@Override
public Callable<SomeObject> setAction() {
return new Callable<SomeObject>() {
@Override
public SomeObject call() throws ... {
return (SomeObject)binding.findSomething(somethingsId);
}
};
}
...
}
我做的其他地方:
Callable<SomeObject> ts = (Callable<SomeObject>) strategy.setAction();
编译器信号:
unchecked conversion warning
required: Callable<SomeObject>
found: Callable
奇怪的是,如果我这样做,就没有警告:
Callable<SomeObject> ts = new Callable<SomeObject>() {
@Override
public SomeObject call() throws ... {
return (SomeObject)binding.findSomething(somethingsId);
}
};
我该如何解决这个问题?我试图改变很多,但我仍然收到警告。请帮忙!
答案 0 :(得分:4)
确保strategy
变量也具有泛型类型信息。
以下内容将导致此警告:
FindingStrategy strategy;
虽然这应该没问题:
FindingStrategy<SomeObject> strategy;
你甚至不需要演员。
答案 1 :(得分:4)
我怀疑你的班级定义应该是
class BindingFindingSomething implements FindingStrategy<SomeObject>