Can I have an abstract builder class in java with method chaining without doing unsafe operations?

You want to declare T as extends AbstractBuilder<T> in AbstractBuilder.

Use an abstract protected method to get this of type T.

abstract class AbstractBuilder<T extends AbstractBuilder<T>> {
    protected abstract T getThis();

    public T foo() {
        // set some property
        return getThis();
    }
}


class TheBuilder extends AbstractBuilder<TheBuilder> {
    @Override protected TheBuilder getThis() {
        return this;
    }
    ...
}

Alternatively, drop the generic type parameter, rely on covariant return types and make the code cleaner for clients (although usually they would be using TheBuilder rather than the largely implementation detail of the base class), if making the implementation more verbose.

Leave a Comment