Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java avoid class cast warning in hierarchical Builder pattern

Tags:

java

generics

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

like image 815
Eric Avatar asked Feb 18 '23 04:02

Eric


2 Answers

As said before, this can't be done, because it is not safe. B extends BaseBuilder<T,B>, but BaseBuilder<T,B> (type of this) does not extend B. 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:

public abstract class BaseBuilder <T, B> {

  abstract public B getB();

  public B setB1(String b1) {
    this.b1 = b1;
    return getB();
  }

  abstract public T build();

  String b1;
}
like image 165
newacct Avatar answered Mar 04 '23 09:03

newacct


Yes; return BaseBuilder<T, B> and force subclasses to override setB1 to return themselves.

like image 25
Louis Wasserman Avatar answered Mar 04 '23 11:03

Louis Wasserman