简体   繁体   English

创建泛型类的公共内部类的实例

[英]Creating instances of public inner classes of generic classes

So I have something like the following: 所以我有以下内容:

public class Enclosing<T extends Comparable<T>> {
    // non-relevant code snipped
    public class Inner {
        private T value;
        public Inner(T t) {
            value = t;
        }
    }
}

Everything compiles and the world is happy. 一切都在汇编,世界也在快乐。 However, whenever I try to create an instance of Enclosing.Inner as follows, I can't: 但是,每当我尝试按如下方式创建Enclosing.Inner的实例时,我都不能:

new Enclosing<Integer>.Inner(5);

The following error happens: 发生以下错误:

Cannot allocate the member type Enclosing<Integer>.Inner using a parameterized compound name; 无法使用参数化复合名称分配成员类型Enclosing<Integer>.Inner ; use its simple name and an enclosing instance of type Enclosing<Integer> . 使用其简单名称和Enclosing<Integer>类型的封闭实例。

It is important to note that I cannot make the inner class static , because it contains a field of type T . 重要的是要注意我不能使内部类static ,因为它包含T类型的字段。

How can I work around this? 我该如何解决这个问题?

To instantiate an inner class , you must first instantiate the outer class. 要实例化内部类 ,必须首先实例化外部类。 Then, create the inner object within the outer object with this syntax: 然后,使用以下语法在外部对象中创建内部对象:

  Enclosing<Integer> outerObject = new Enclosing<Integer>();
  Enclosing<Integer>.Inner innerObject = outerObject.new Inner();

The ugly syntax suggests a code smell in this design. 丑陋的语法暗示了这种设计中的代码味道。 There should probably be a factory method of some kind in the Enclosing class ( getInner or something) and the inner class should probably implement a public interface if it is being used from outside its enclosing class. getInner类( getInner或者其他)中可能应该有某种工厂方法,如果从其封闭类之外使用它,内部类可能应该实现一个公共接口。

just ran into the same problem, solved it the following way in java7 刚遇到同样的问题,在java7中解决了以下问题

public class Test {
    static class A<T> {
        public class B {

        }
    }
    A<String> a = new A();
    class C extends A.B {
        C() {
            Test.this.a.super();
        }
    }
    public void test() {
        C c = new C();
        A.B b = this.a.new B();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM