【发布时间】:2020-06-22 11:37:12
【问题描述】:
在创建具有泛型类型的类时,似乎不可能使用私有类作为类型参数,即使该类是泛型类型的内部类。考虑这段代码:
import java.util.Iterator;
import test.Test.Type;
public class Test implements Iterable<Type> {
@Override
public Iterator<Type> iterator() {return null;}
static class Type {}
}
上面的例子可以编译,而同样的例子在Type是私有的时候不编译:
import java.util.Iterator;
// ERROR: The type test.Test.Type is not visible
import test.Test.Type;
// ERROR: Type cannot be resolved to a type
public class Test implements Iterable<Type> {
@Override
// ERROR: The return type is incompatible with Iterable<Type>.iterator()
public Iterator<Type> iterator() {return null;}
private static class Type {}
}
为什么不能使用私有类作为其封闭类的类型参数?尽管是私有的,但我认为 Type 类应该在 Test 类中可见。
【问题讨论】:
-
您希望
iterator()的调用者对结果做什么?它无法获取结果类型,因为它不可见。 -
这只是一个例子。在我的原始代码中,我创建了一个带有内部中间类型的
Collector——它只在类本身中使用。我只是试图使示例尽可能简单,以专注于行为,而不是使用大量不相关的代码行。所以我选择了Iterable接口 -
我在查看JLS 6.3,但没有找到确切的参考,我很确定
T超出了范围。
标签: java generics class-visibility