interface A {
String n();
}
class B implements A {
@Override
public String n() { return "asdf"; }
}
interface C<T extends A> {
T m(T t);
}
class D implements C<B> {
@Override
public B m(B b) {
return b;
}
}
Class<C<? extends A>> x = D.class;
Run Code Online (Sandbox Code Playgroud)
最后一行有错误
Type mismatch: cannot convert from Class<D> to Class<C<? extends A>>
Run Code Online (Sandbox Code Playgroud)
这看起来对我很好,但也许我错过了类型通配符如何工作的一些微妙之处.有没有办法可以改变最后一行的类型?我需要这个参考,因为我打算稍后这样做:
B b = new B();
A y = x.newInstance().m(b);
Run Code Online (Sandbox Code Playgroud)
这也有错误
The method m(capture#1-of ? extends A) in the type C<capture#1-of ? extends A> is not applicable for the arguments (B)
Run Code Online (Sandbox Code Playgroud)
但是,如果我在没有通配符和捕获的情况下使用它,它可以正常工作:
A z = D.class.newInstance().m(b);
Run Code Online (Sandbox Code Playgroud)
不幸的是,我现在有点坚持这个,任何帮助将不胜感激.
编辑:删除this.参考
编辑:将x更改为
Class<? extends C<? extends A>> x = D.class;
Run Code Online (Sandbox Code Playgroud)
它的工作原理.但仍然有错误x.newInstance().m(b)
The method m(capture#2-of ? extends A) in the type Test.C<capture#2-of ? extends A> is not applicable for the arguments (B)
Run Code Online (Sandbox Code Playgroud)
是的,只关注最后一部分:
然而仍然在x.newInstance()上得到错误.m(b)
Run Code Online (Sandbox Code Playgroud)The method m(capture#2-of ? extends A) in the type Test.C<capture#2-of ? extends A is not applicable for the arguments (B)
确实 - 这是完全合理的.因为你的代码中没有任何内容表明你实际上有一个C<B>.所有的编译器知道的是,newInstance返回的实例一些类型,它实现C<X>了某种类型的X一个实现A.怎么会知道那是B什么?
如果你想打电话m(b),你需要一个C<B>,这意味着你的声明需要
Class<? extends C<B>> x = D.class;
Run Code Online (Sandbox Code Playgroud)
此时,方法调用将干净地编译.目前还不是很清楚你想要达到的目标,或者这对你来说是否足够好 - 但希望它能解释为什么你会得到你得到的错误......
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |