创建公共内部类的泛型类的实例 [英] Creating instances of public inner classes of generic classes

查看:196
本文介绍了创建公共内部类的泛型类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class Enclosing< T extends Comparable< T>> {
//不相关的代码片断
公共类内部{
私有T值;
public Inner(T t){
value = t;
}
}
}

快乐。但是,每当我尝试创建一个 Enclosing.Inner 的实例时,我不能:

  new Enclosing< Integer> .Inner(5); 

发生以下错误:


无法使用参数化化合物名称分配成员类型包含<整数> .Inner ;使用它的简单名称和一个封闭的类型 Enclosing< Integer>


重要的是要注意,我不能让内部类 static ,因为它包含一个 T 类型的字段。



我该如何解决这个问题?

解决方案

要实例化一个内部类,您必须首先实例化外部类。然后,使用以下语法在外部对象中创建内部对象:

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

丑陋的语法在本设计中暗示了一种代码味道。在Enclosing类( getInner 或其他)中可能有某种工厂方法,而内部类应该可以实现一个公共接口,如果它从外部使用附上课程。

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:

new Enclosing<Integer>.Inner(5);

The following error happens:

Cannot allocate the member type Enclosing<Integer>.Inner using a parameterized compound name; use its simple name and an enclosing instance of type Enclosing<Integer>.

It is important to note that I cannot make the inner class static, because it contains a field of type 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.

这篇关于创建公共内部类的泛型类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆