当创建具有泛型类型的类时,似乎不可能使用私有(private)类作为类型参数,即使该类是泛型类型的内部类。考虑这段代码:
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
为私有(private)时,同一示例无法编译:
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 {}
}
为什么不能使用私有(private)类作为其封闭类的类型参数?尽管是私有(private)的,但在我看来,Type
类应该在 Test
类中可见。
最佳答案
我可以假设这是因为如果将 Type 设为私有(private),则无法获得 iterator () 的结果,因为 Type 是看不见的。我可能是错的。
关于java - 使用私有(private)成员参数化通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60619887/