我有课
public class DiaryItem extends AbstractInfoElement { ... };
public class EventItem extends AbstractInfoElement { ... };
public class StickerItem extends AbstractInfoElement { ... };
public class TodoItem extends AbstractInfoElement { ... };
我已经重写了方法来使用此参数执行某些操作:
class DBEngine {
public long add(EventItem item){ ... };
public long add(StickerItem item){ ... };
public long add(TodoItem item){ ... }
}
然后我实现了模板类以通用方式操作类型
public class AddItemCommand<T extends AbstractInfoElement>{
private final T item;
public AddItemCommand(T item) {
this.item = item;
}
void doSmth() {
add(item);
}
}
我认为编译器将 T 解析为所需类型,但我遇到了问题:
Error:(78, 45) error: no suitable method found for add(T)
method DBEngine.add(DiaryItem) is not applicable
(argument mismatch; T cannot be converted to DiaryItem)
method DBEngine.add(EventItem) is not applicable
(argument mismatch; T cannot be converted to EventItem)
method DBEngine.add(StickerItem) is not applicable
(argument mismatch; T cannot be converted to StickerItem)
method DBEngine.add(TodoItem) is not applicable
(argument mismatch; T cannot be converted to TodoItem)
where T is a type-variable:
T extends AbstractInfoElement declared in class AddItemCommand
我的目标是避免在这些情况下过度编码:
AddItemCommand<DiaryItem> cmdDiary = new AddItemCommand<DiaryItem>(new DiaryItem);
cmdDiary.doSmth();
应该打电话
DBEngine.add(DiaryItem item);
和
AddItemCommand<TodoItem> cmdTodo = new AddItemCommand<TodoItem>(new TodoItem);
cmdTodo.doSmth();
应该打电话
DBEngine.add(TodoItem item);
仅此而已,但不起作用...这些问题是在编译时...
顺便说一句...请原谅我糟糕的英语
最佳答案
从您的错误消息来看,您似乎只有具体子类的 add
方法,DiaryItem
、EventItem
、StickerItem
和 TodoItem
,但随后您尝试
使用 T extends AbstractInfoElement
类型的参数调用 add。
这不起作用,因为 T(“AbstractInfoElement 的任何子类”)与任何一个特定子类都不匹配。
编辑:请注意,Java 仅对静态类型进行分派(dispatch)(即,根据编译时已知的类型选择要调用的重载方法),因此它无法知道 T 是否匹配子类之一。
(参见例如 How does Java method dispatch work with Generics and abstract classes? 、 Java Generic / Type Dispatch Question 、 Method overloading and generics )
关于Java 泛型 : Why compiler can not resolve type T to inherited type in method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536756/