【问题标题】:Parameterize Generic Type with private member使用私有成员参数化通用类型
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是因为您的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 {}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多