Java从内部接口访问外部类的泛型参数
考虑一下代码:
public class A<T extends X> {
public static interface Delegate {
void doMagic(T t); // why can't I access "T" here?
}
public A(Delegate delegate) { ... }
}
...
public class TheDelegate implements A<Y> { ... }
...
A<Y> a = new A<Y>(new A<Y>.Delegate() {
@Override
public void doMagic(Y y) {
...
}
});
为什么我无法从 Delegate
接口访问 T
?
Consider the code:
public class A<T extends X> {
public static interface Delegate {
void doMagic(T t); // why can't I access "T" here?
}
public A(Delegate delegate) { ... }
}
...
public class TheDelegate implements A<Y> { ... }
...
A<Y> a = new A<Y>(new A<Y>.Delegate() {
@Override
public void doMagic(Y y) {
...
}
});
Why can't I access T
from Delegate
interface?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为你的内部接口是静态的。泛型参数仅适用于 A 的实例,而不适用于类,因此 T 的范围是 A 的非静态范围。
如果您不知道,所有接口和枚举在 Java 中是静态的,即使它们没有声明为静态并且位于另一个类中。因此,无法通过接口来解决这个问题。
另请参阅此答案。
编辑:史蒂文的答案是正确的。但是,您的用户代码将如下所示:
It's because your inner interface is static. The generic parameter only applies to an instance of
A
as opposed to applying to the class, so the scope of T is the non-static scope of A.In case you didn't know, all interfaces and enumerations are static in Java, even if they are not declared as static and are inside another class. Therefore there is no way to work around this with an interface.
See this answer also.
EDIT: Steven's answer is correct. However, your user code will look like this:
您的内部接口可以有自己的通用边界。尝试将其声明并用作
Delegate
,它应该可以正常工作。Your inner interface can have its own generic bounds. Try declaring and using it as
Delegate<T>
and it should work fine.