gpt4 book ai didi

java - 如何在 Java 中使用内部类实例化递归绑定(bind)泛型?

转载 作者:太空狗 更新时间:2023-10-29 22:57:53 26 4
gpt4 key购买 nike

我想要以内部类作为参数的通用外部类。我期待的是,我将从基类派生并使用它的内部,或者也派生内部。在每个级别上,我都希望从当前派生级别开始限制内部类的使用。

不幸的是,我在使用该模式时遇到了各种错误和警告,以至于我无法想象如何使用它。

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
}

}

如何正确使用这个模式?

最佳答案

我相信你可以简单地做

    DerivedCorpus1<?>

在通配符捕获期间,它变为

    DerivedCorpus1<x> where x extends Corpus<x>.Element

正确界定。

在你的例子中

    DerivedCorpus1<? extends Corpus<?>.Element>

在通配符捕获期间,它变为

    DerivedCorpus1<x> where x extends Corpus<x>.Element
and x extends Corpus<?>.Element

显然,extends Corpus<?>.Element条款是多余的。

关于java - 如何在 Java 中使用内部类实例化递归绑定(bind)泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com