考虑一下代码:
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) {
...
}
});
Run Code Online (Sandbox Code Playgroud)
为什么我不能T从Delegate界面访问?
这是因为你的内部接口是静态的.泛型参数仅适用于A与应用于类相反的实例,因此T的范围是A的非静态范围.
如果您不知道,所有接口和枚举在Java中都是静态的,即使它们未声明为静态且位于另一个类中.因此,无法使用界面解决此问题.
编辑:史蒂文的答案是正确的.但是,您的用户代码将如下所示:
// Note the extra declaration of the generic type on the Delegate.
A<Integer> a = new A<Integer>(new A.Delegate<Integer>() {
@Override
public Integer myMethod() {
return null;
}
});
Run Code Online (Sandbox Code Playgroud)
您的内部接口可以有自己的通用边界.尝试声明并使用它Delegate<T>,它应该工作正常.
| 归档时间: |
|
| 查看次数: |
1165 次 |
| 最近记录: |