java - 使用私有(private)成员参数化通用类型

标签 java generics class-visibility

当创建具有泛型类型的类时,似乎不可能使用私有(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/

相关文章:

swift - 泛型的泛型? A<T<U>> 类?

java - 关于在另一个接口(interface)中实现泛型接口(interface)的误解

java - 是否可以在 Netbeans 的项目 View 中显示一个类是公共(public)类还是包私有(private)类?

C++:私有(private)嵌套类类型的公共(public)成员

module - 如何在 Rust 中相互隐藏兄弟模块?

java - 如何添加透视监听器

java - Web 客户端的 ObjectMapper

java - Eclipse 插件无法正常工作

java - MQTT 客户端在重新启动时重复最后一条消息

java - 获取通用数组的大小