Using @NonNull with @Builder

2,720 views
Skip to first unread message

jilt3d

unread,
Oct 4, 2013, 7:02:50 AM10/4/13
to project...@googlegroups.com
I have the following class:

@Builder
public final class Foo {
    @NonNull
    private final String bar;
}

and the following test returns: java.lang.AssertionError: Expected exception: java.lang.NullPointerException

public final class TestFoo {
    @Test(expected = NullPointerException.class)
    public void shouldThrowNullPointerExceptionIfBarIsNull() {
        Foo.builder().bar(null);
    }
}

Do I miss something or @NonNull doesn't play with the @Builder?

Reinier Zwitserloot

unread,
Oct 4, 2013, 7:47:44 AM10/4/13
to project...@googlegroups.com
This is on purpose.

Once you call the build() method, you'll get that exception. We intentionally allow you to set the field to 'null' in the builder, for a number of reasons:

* The builder's field cannot be called @NonNull, as it starts out as null. There is no practical way we can let you specify the initial value.
* It's a builder. The entire point of one is to be the context for the time between the thought of 'I want to make a complex object that has various prerequisites' and 'It is complete; I sign off on the requisites'. As you call methods on the builder, you're in the limbo state where the object is not valid. Throwing exceptions during this time is a bad idea as it's a known and workable state. For example, while this is reaching a little bit, you can call a set method on the builder to set the field back to null, as a way to say: Okay, right now I want any calls to build() to just fail, until someone remembers to actually set this to a valid value later.

Basically, update your test to expect the NPE when calling build().
Reply all
Reply to author
Forward
0 new messages