正确使用无界wilcard泛型 [英] Proper use of unbounded wilcard generics

查看:156
本文介绍了正确使用无界wilcard泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用无界通配符,因为我有一些Callable's返回一个Object,但我对这个对象不感兴趣(它们返回null,我只是使用Callable而不是Runnable来引发checked异常)。

原则上我想这样做:

pre $ CompletionService<?> ecs = ...
可调用<?> = ...
未来<?> f = ecs.submit(c);

但是在这里我得到一个错误:

< blockquote>

类型中提交(Callable< capture#1-of?>) CompletionService< capture#1-of?>
不适用于参数
Callable< capture#2-?>>


稍后我只想调用f.get()来处理在提交的任务中抛出的异常。



那么处理这个问题的正确方法是什么?解析方案

通配符不合适这里。 (还要注意的是,如果你有两个通配符它们不匹配,就好像你有一个名为 T U

标准方法是使用< Void>


I'm trying to use unbounded wildcards because I have some Callable's that return an Object but I'm not interested in the object (they return null and I'm just using Callable instead of Runnable to be able to throw checked Exceptions).

So in principle I want to do this:

CompletionService<?> ecs = ...
Callable<?> = ...
Future<?> f = ecs.submit(c);

But here I get an error saying:

The method submit(Callable<capture#1-of ?>) in the type CompletionService<capture#1-of ?> is not applicable for the arguments (Callable<capture#2-of ?>)

Later on I just want to call f.get() to handle exceptions thrown in the submitted task.

So what is the proper way to handle this?

解决方案

Wildcards are not appropriate here. (Also note that if you have two wildcards they don't match as such, just as if you have generic parameters named T and U.)

The standard approach is to use <Void>.

这篇关于正确使用无界wilcard泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆