在 Java 中使用泛型参数扩展抽象方法(必须扩展泛型 class)
Extending abstract method with generic parameter (that must extend generic class) in Java
假设我有一个通用构建器类型:
public abstract class Builder<T> {
public abstract T build();
}
然后是 Foo class 和它的构建器,它扩展了 Builder:
public class Foo {
// stuff
}
public class FooBuilder extends Builder<Foo> {
public Foo build() {
return new Foo();
}
}
我还有一个抽象的通用处理程序类型:
public abstract class Handler<T> {
public abstract <U extends Builder<T>> void handle(U builder);
}
最后是一个 FooHandler:
public class FooHandler extends Handler<Foo> {
@Override
public void handle(FooBuilder builder) {
// do something
}
}
问题是 FooHandler 的 handle() 未被识别为覆盖 Handler 的 handle():Method does not override method from its superclass
。可以这样做吗?
将类型参数移动到 class 级别
abstract class Handler<T, U extends Builder<T>> {
public abstract void handle(U builder);
}
class FooHandler extends Handler<Foo, FooBuilder> {
@Override
public void handle(FooBuilder builder) {
// do something
}
}
假设我有一个通用构建器类型:
public abstract class Builder<T> {
public abstract T build();
}
然后是 Foo class 和它的构建器,它扩展了 Builder:
public class Foo {
// stuff
}
public class FooBuilder extends Builder<Foo> {
public Foo build() {
return new Foo();
}
}
我还有一个抽象的通用处理程序类型:
public abstract class Handler<T> {
public abstract <U extends Builder<T>> void handle(U builder);
}
最后是一个 FooHandler:
public class FooHandler extends Handler<Foo> {
@Override
public void handle(FooBuilder builder) {
// do something
}
}
问题是 FooHandler 的 handle() 未被识别为覆盖 Handler 的 handle():Method does not override method from its superclass
。可以这样做吗?
将类型参数移动到 class 级别
abstract class Handler<T, U extends Builder<T>> {
public abstract void handle(U builder);
}
class FooHandler extends Handler<Foo, FooBuilder> {
@Override
public void handle(FooBuilder builder) {
// do something
}
}