Java从内部接口访问外部类的泛型参数

时间:2011-10-25 07:03:26

标签: java generics

考虑代码:

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) {
    ...
  }
});

为什么我无法从T界面访问Delegate

2 个答案:

答案 0 :(得分:6)

这是因为你的内部接口是静态的。泛型参数仅适用于A的实例,而不是应用于类,因此T的范围是A的非静态范围。

如果您不知道,所有接口和枚举在Java中都是静态的,即使它们未声明为静态且位于另一个类中。因此,无法使用界面解决此问题。

See this answer also.

编辑:史蒂文的回答是正确的。但是,您的用户代码如下所示:

// 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;
  }
});

答案 1 :(得分:5)

您的内部接口可以有自己的通用边界。尝试声明并将其用作Delegate<T>,它应该可以正常工作。

相关问题