请帮助解决有关泛型的问题。我尝试了很多方法,但它仍然没有用。
问题是:
public static void main(String[] args) {
Utils.execute(new TestAction(), new TestCallBack());
}
编译器显示错误:
The method execute(Action<?>, CallBack<?,Action<?>>) in the type Utils is not applicable for the arguments (ImplementClass.TestAction, ImplementClass.TestCallBack)
我的课程是:
行动类:
public abstract class Action<R> {
public R getResult() {
return null;
}
}
TestAction类是:
class TestAction extends Action<String> {
@Override
public String getResult() {
return super.getResult();
}
}
回调课程是:
public interface CallBack<R, A extends Action<R>> {
public void onCall(A action);}
TestCallback类是:
class TestCallBack implements CallBack<String, TestAction> {
@Override
public void onCall(TestAction action) {
}
}
和Utils课程是:
public class Utils {
public static void execute(Action<?> action, CallBack<?, Action<?>> callback) {
}
}
非常感谢。
答案 0 :(得分:1)
execute
方法的第二个参数是CallBack<?, Action<?>>
,Action
表示Action
类本身,不允许它的子类。您需要的是 - ? extends Action<?>
,这意味着Action
或其中的某些子类。
尝试更改方法签名 -
public static void execute(Action<?> action, CallBack<?, ? extends Action<?>> callback) {
注意:
泛型不是共变体。例如,采用如下方法 -
static void method(List<Object> l) {}
不允许进行如下调用 -
method(new ArrayList<String>());
答案 1 :(得分:1)
你需要改变两件事,
TestCallBack 应该是这样的 -
public static class TestCallBack implements CallBack<String, Action<String>> {
@Override
public void onCall(Action<String> action) {
}
}
和 Utils 应该是这样的 -
public static class Utils {
// You need to ensure the same type, not just try and accept anything.
public static <T> void execute(Action<T> action, CallBack<?, Action<T>> callback) {
}
}
或使用名为Question
-
public abstract class Action<R> {
public R getResult() {
return null;
}
}
public class TestAction extends Action<String> {
@Override
public String getResult() {
return super.getResult();
}
}
public interface CallBack<R, A extends Action<R>> {
public void onCall(A action);
}
public class TestCallBack implements CallBack<String, TestAction> {
@Override
public void onCall(TestAction action) {
}
}
public class Utils {
public void execute(Action<?> action, CallBack<?, ? extends Action<?>> callback) {
}
}
public static void main(String[] args) {
Question question = new Question();
question.new Utils().execute(question.new TestAction(), question.new TestCallBack());
}