我有这样的设置:
public final class RequestContext<T extends Cache> {
T roleSpecificCache;
public static final class Spec implements Supplier<RequestContext> {
private Spec() {
}
T roleSpecificCache; // << Getting error here
}
private RequestContext(Spec b) {
this.roleSpecificCache = b.roleSpecificCache; // << I want to do this
}
}
但是,在 T roleSpecificCache
行上,我收到以下错误
:
RequestContext.this cannot be referenced from a static context
我理解出现此错误的原因(即两个类之间没有直接链接),但不知道如何修复它。我希望最终能够做我正在做的事情。
此外,我无法使 Spec
成为非静态(超出我的控制范围)。
最佳答案
您需要参数化Spec
:
public final class RequestContext<T extends Cache> {
T roleSpecificCache;
public static final class Spec<T extends Cache>
implements Supplier<RequestContext<T>> {
private Spec() {
}
T roleSpecificCache;
}
private RequestContext(Spec<T> b) {
this.roleSpecificCache = b.roleSpecificCache;
}
}
由于raw type argument to Supplier
, which should be avoided,看起来似乎一开始就应该是这样的。 .
关于java - 使用与封闭类具有相同泛型类型的静态嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433894/