我经常发现自己想要编写表单的泛型类定义
public class Foo<ActualType extends Foo<ActualType>>
Run Code Online (Sandbox Code Playgroud)
例如,在这样的设置中:
public interface ChangeHandler<SourceType> {
public void onChange(SourceType source);
}
public class Foo<ActualType extends Foo<ActualType>> {
private final List<ChangeHandler<ActualType>> handlers = new ArrayList<>();
public void addChangeHandler(ChangeHandler<ActualType> handler) {
handlers.add(handler);
}
@SuppressWarnings("unchecked")
protected void reportChange() {
for (ChangeHandler<ActualType> handler: handlers)
handler.onChange((ActualType) this);
}
}
public class Bar extends Foo<Bar> {
// things happen in here that call super.reportChange();
}
public static void main(String[] args) throws IOException {
Bar bar = new Bar();
bar.addChangeHandler(new ChangeHandler<Bar>() { …Run Code Online (Sandbox Code Playgroud) 我有一个构建器类,它从大多数方法返回以允许菊花链.为了使这个工作与子类,我希望父方法返回子的实例,以便子方法可用于链到最后.
public class BaseBuilder<T extends BaseBuilder<T>> {
public T buildSomething() {
doSomeWork();
/* OPTION #1: */ return this; // "Type mismatch: cannot convert from BaseBuilder<T> to T"
/* OPTION #2: */ return T.this; // "Type mismatch: cannot convert from BaseBuilder<T> to T"
/* OPTION #3: */ return (T) this; // "Type safety: Unchecked cast from SqlBuilder<T> to T"
}
}
public class ChildBuilder extends BaseBuilder<ChildBuilder> {}
Run Code Online (Sandbox Code Playgroud)
选项#1和#2导致编译错误,选项#3导致警告(尽管可以抑制@SuppressWarnings("unchecked")).这里有更好的方法吗?我怎样才能安全地将Basebuilder投降给Childbuilder?