当类型为通配符时,如何使用泛型结果作为泛型参数?
[更新] 真实情况比我最初的问题看起来要复杂一些。我对代码做了一些更改以反映这一点。[/更新]
我对以下行为有点困惑。给定如下代码:
interface Inter<T> {
T makeT();
void useT(T t);
}
public class Foo {
public void bar(Qux q) {
Inter<?> x = getInterForQux(q);
x.useT(x.makeT());
}
Inter<?> getInterForQux(Qux q) {
if( someTest(q) ) {
return (Inter<Integer>) mkAnInterInt();
} else {
return (Inter<Double>) mkAnInterDouble();
}
}
}
Javac 给我错误:
在 Inter
中使用 T(capture#478 of ?)无法应用于 (java.lang.Object)
而 Eclipse 给了我:
类型Inter
中的方法useT(capture#1-of ?)是 不适用于参数 (捕获#2-of?)
显然,无论T
是什么,makeT()
的结果类型与useT()的参数类型相同
。为什么我不能这样做?有解决方法吗?
[UPDATE] The real situation was a bit more complicated than my initial question made it seem. I've changed the code a bit to reflect that.[/UPDATE]
I'm a bit stumped by the following behavior. Given code like:
interface Inter<T> {
T makeT();
void useT(T t);
}
public class Foo {
public void bar(Qux q) {
Inter<?> x = getInterForQux(q);
x.useT(x.makeT());
}
Inter<?> getInterForQux(Qux q) {
if( someTest(q) ) {
return (Inter<Integer>) mkAnInterInt();
} else {
return (Inter<Double>) mkAnInterDouble();
}
}
}
Javac gives me the error:
useT(capture#478 of ?) in Inter<capture#478 of ?> cannot be applied to (java.lang.Object)
Whereas Eclipse gives me:
The method useT(capture#1-of ?) in the type Inter<capture#1-of ?> is
not applicable for the arguments
(capture#2-of ?)
Obviously, no matter what T
is the result type of makeT()
is the same as the parameter type of useT()
. Why can't I do this? Is there a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您使用通配符时,编译器无法看到
x.makeT()
的返回类型和x.useT()
的参数类型是否相同。为了保证它们是相同的,你应该在这里使用泛型方法:When you use wildcard, compiler can't see that the return type of
x.makeT()
and the parameter type ofx.useT()
are the same. In order to guarantee that they are the same, you should use generic method here:这是合乎逻辑的,因为
Inter.makeT()
可以返回任何内容,而Inter.useT(..)
会消耗任何内容,但是两者任何事情都可以不同。这样就可以解决这个问题:
This is logical, since
Inter<?>.makeT()
can return anything, andInter<?>.useT(..)
consumes anything, but the two anythings can be different.That would fix it:
使用捕获助手:
这为您提供了与您想要的
bar
相同的签名Use a capture helper:
This gives you the same signature for
bar
as you want