英文:
Generic Casting Issue
问题
我定义了一个通用接口,其中包含供应商和消费者:
public interface ItemProcessor<T> {
void processItem(T task);
T getNextItem();
}
然而,在使用这个接口时我遇到了问题:
List<ItemProcessor<?>> itemProcessors = new ArrayList<>();
// 将 itemProcessors 添加到列表中
for (ItemProcessor<?> itemProcessor : itemProcessors) {
itemProcessor.processItem(itemProcessor.getNextItem());
}
这给我带来了编译错误:所需类型:? 的捕获,提供的类型:? 的捕获
。由于我正在使用同一个 item processor 对象,Java 不应该能够推断出类型是相同的吗?
英文:
I have defined a generic interface that has a supplier and a consumer:
public interface ItemProcessor<T> {
processItem(T task);
T getNextItem();
}
However, I am running into issues when using this interface:
List<ItemProcessor<?>> itemProcessors = new ArrayList<>();
// add itemProcessors to list
for (ItemProcessor<?> itemProcessor : itemProcessors) {
itemProcessor.processItem(itemProcessor.getNextItem());
}
This give me the compile error Required type: capture of ?, Provided type: capture of ?
Since I'm using the same item processor object, shouldn't java be able to infer that the type is the same?
答案1
得分: 1
你可以通过所谓的“通配符捕获方法”来稍微修改这个代码:
private static <T> void process(ItemProcessor<T> item) {
item.processItem(item.getNextItem());
}
然后将调用更改为:
for (ItemProcessor<?> itemProcessor : itemProcessors) {
process(itemProcessor);
}
我在这里有两个答案这里和这里,例如解释了为什么会发生这种情况。但也可以参考官方的 Oracle 教程来了解更多信息。
英文:
You can hack this a bit, via a so called "wildcard capture method":
private static <T> void process(ItemProcessor<T> item) {
item.processItem(item.getNextItem());
}
And then change your call to:
for (ItemProcessor<?> itemProcessor : itemProcessors) {
process(itemProcessor);
}
I have two answers here and here, for example explaining why this happens. But there is also the official Oracle tutorial explaining things
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论