静态嵌套类作为泛型类型绑定不起作用 [英] Static nested class as generic type bound doesn't work
问题描述
文件 AbstractContainer.java
包容器;
import static container.AbstractContainer。*;
公共抽象类AbstractContainer< ElementType extends AbstractElement> {
public static abstract class AbstractElement {
}
}
文件 ConcreteElement.java
包容器;
导入静态容器.ConcreteContainer。*;
import static container.AbstractContainer。*;
public class ConcreteContainer extends AbstractContainer< ConcreteElement> {
public static class ConcreteElement extends AbstractElement {
}
}
这段代码给了我一个编译错误:
java:type参数container.ConcreteContainer.ConcreteElement不在类型变量的范围内ElementType
但IDE没有发现任何问题(IDEA 12)。
第一:这是怎么回事?第二个问题,在 AbstractContainer.java 中,为什么我有静态导入嵌套类,这显然是在范围内,以泛型类型使用它( extends AbstractElement
而不是 extends AbstractContainer.AbstractElement $第一个问题 - 可能是一个编译器错误。
$ b $
第二个问题 - 可能是由于技术性原因:
ht tp://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.3
在类类型C(§8.1.6)中声明或继承的成员
m
的声明范围是C <例如
$ b@SomeAnnotation( M.class)
class C
< T扩展M>
{
static class M {}
}
代码是非法的,因为
M
在C
的主体之外,注解和类型参数中使用。
在Java 5之前,没有注释/泛型,因此C的整个主体涵盖了所有地方,M可以被明智地引用。但是现在这个规则已经过时了,我们应该真的扩大
M
的范围。我看不出有任何问题。File AbstractContainer.java
package container; import static container.AbstractContainer.*; public abstract class AbstractContainer<ElementType extends AbstractElement> { public static abstract class AbstractElement { } }
File ConcreteElement.java
package container; import static container.ConcreteContainer.*; import static container.AbstractContainer.*; public class ConcreteContainer extends AbstractContainer<ConcreteElement> { public static class ConcreteElement extends AbstractElement { } }
This code gives me a compile error:
java: type argument container.ConcreteContainer.ConcreteElement is not within bounds of type-variable ElementType
but the IDE doesn't see any problems (IDEA 12).
First: What is going on here?
Second question, In AbstractContainer.java why do I have to static import the nested class, that's obviously in scope, to use it in the generic type (
extends AbstractElement
instead ofextends AbstractContainer.AbstractElement
) ?解决方案First question - probably a compiler bug.
Second question - probably due to technicality:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.3
The scope of a declaration of a member
m
declared in or inherited by a class type C (§8.1.6) is the entire body of CFor example
@SomeAnnotation(M.class) class C <T extends M> { static class M{} }
the code is illegal, because
M
is used outside the body ofC
, in annotation, and in type parameter.Prior to Java 5, there's no annotation/generics, therefore "the entire body of C" covers all places "M" can be sensibly referenced. But now the rule is outdated, we should really extend the scope of
M
a little bit; I don't see any problem in doing that.这篇关于静态嵌套类作为泛型类型绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!