自绑定泛型类型,具有流畅的接口和继承

Ste*_*fan 9 java generics inheritance fluent-interface

我正在使用一个流畅的继承接口.我声明基类Constructor受到保护,所以你不能创建一个Foo <Bar>,它会在调用add()时导致ClassCastException.但我遇到了返回新Foo实例的静态方法的问题.

public class Foo<T extends Foo<T>> // if i change to extends Foo i only get warnings
{
        public static Foo<Foo> createFoo() // <-- error
        {
                return new Foo<Foo>(); // <-- error
        }

        protected Foo() {}

        public T add()
        {
                //...
                return (T)this;
        }
}

public class Bar extends Foo<Bar>
{
        public Bar sub()
        {
                //...
                return this;
        }
}
Run Code Online (Sandbox Code Playgroud)

这主要是Fluent Interfaces,Domain-specific language和Generics中的练习(个人而不是家庭作业),所以请不要问我需要它.

编辑:Eclipse错误

Bound mismatch: The type Foo is not a valid substitute for the bounded parameter <T extends Foo<T>> of the type Foo<T>
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 3

您本质上有一个递归类型声明。

Foo<T extends Foo<T>>

假设您有一个Foo<Foo>. 这意味着T映射到Foo. 但Foo不是 的子类型Foo<T>,在本例中是Foo<Foo>,所以您真正要寻找的是Foo<Foo<Foo>>。但是等一下,最里面的部分Foo没有输入,所以我猜它是Foo<Foo<Foo<Foo>>>......哦,算了!

为了让它看起来更容易理解,请考虑一下您是否有Foo<T extends List<T>>。您可以T在 的声明/实例化中使用什么FooList<String>List<List>

编辑

看来您找到了一种“打破”递归循环的方法。你最终需要达到具体化的类型。就像您发现ConcreteFoo对您有用一样,您也可以在上面的示例中使用一些可以打破递归循环的List类。ConreteListOfItself implements List<ConreteListOfItself>