2

在创建具有泛型类型的类时,似乎不可能使用私有类作为类型参数,即使该类是泛型类型的内部类。考虑这段代码:

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

4

2 回答 2

1

我可以假设这是因为如果你将 Type 设为私有,你将无法获得 iterator() 的结果,因为 Type 是看不见的。我可能是错的。

于 2020-03-10T14:45:42.557 回答
1

这是因为您的Test班级之外的任何代码都无法访问Type.

如果您限制返回Iterator私有可见性的方法,它将编译:

import java.util.Iterator;

public class Test {

    public void doTest() {
        Iterator<Type> it = iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

    private Iterator<Type> iterator() {
        return null;
    }

    private static class Type {}
}
于 2020-03-10T15:16:55.117 回答