如何在Java中使用内部类实例化递归绑定泛型?
我希望使用具有内部类作为参数的泛型外部类。我期望,我将从基类派生,要么使用它的内部,要么派生内部。在每个级别,我都希望从当前的派生级别开始限制内部类的使用。
不幸的是,我在使用该模式时遇到了各种错误和警告,因此我无法想象如何使用它。
package tests.java;
public class Try_GenericInnerRecursion {
// base class, consisting of outer and inner parts
public static class Outer1<E extends Outer1<E>.Inner1> {
public class Inner1 {
}
public void addElement(E e) {
System.out.println("Added " + e.toString());
}
}
// extending outer, but not inner
public static class Outer2<E extends Outer1<E>.Inner1> extends Outer1<E>{
}
// extending both outer and inner
public static class Outer3<E extends Outer3<E>.Inner3> extends Outer1<E>{
public class Inner3 extends Inner1 {
}
}
// extending both outer and inner and stopping extension
public static class Outer4 extends Outer1<Outer4.Inner4> {
public class Inner4 extends Outer1<Inner4>.Inner1 {
}
}
// instantiating
public static void main(String[] args) {
Outer1<Outer1.Inner1> a1; // WARNING: Outer1.Inner1 is a raw type
a1 = new Outer1<Outer1.Inner1>(); // WARNING: Outer1.Inner1 is a raw type
Outer1<?> a2; // OK
a2 = new Outer1<?>(); // ERROR: Cannot instantiate the type Outer1<?>
Outer1<Outer1<?>.Inner1> a3; // ERROR: Bound mismatch: The type Outer1<?>.Inner1 is not a valid substitute for the bounded parameter <E extends Outer1<E>.Inner1> of the type Outer1<E>
Outer1<? extends Outer1<?>.Inner1> a4; // OK
a4 = new Outer1<Outer1.Inner1>(); // ERROR: Type mismatch
Outer2<Outer1.Inner1> b1; // WARNING: Outer1.Inner1 is a raw type
b1 = new Outer2<Outer1.Inner1>(); // WARNING: Outer1.Inner1 is a raw type
// and so on
}
}
如何正确使用此模式?