Is there a way to avoid the unchecked class cast in this hierarchical Builder pattern?
public abstract class BaseBuilder <T, B extends BaseBuilder<T,B>> {
public B setB1(String b1) {
this.b1 = b1;
return (B) this; // can I make this unchecked cast go away?
}
abstract public T build();
String b1;
}
and no, the answer is not:
return B.class.cast(this);
and yes, I know I could use @SuppressWarnings
As said before, this can’t be done, because it is not safe.
BextendsBaseBuilder<T,B>, butBaseBuilder<T,B>(type ofthis) does not extendB. Recursive bounds are almost NEVER useful in Java, and do not give you the self-type. You should get rid of it.You can add an abstract method such that implementing classes must give an instance of
B: