There's no need to use a special wrapper class for that. If you don't want to allow something to be null
, ensure it isn't null
the moment it's given to you with a check. You can do this with standard Java:
if (arg == null)
throw new NullPointerException();
this.string = arg;
Or with Guava, you can use the Preconditions class to simplify it to:
this.string = checkNotNull(arg); // using static import
In r10 of Guava, coming sometime before too long, you could also use an Optional<T> (immutable) or a Holder<T> (mutable). These aren't necessarily exactly what you're looking for since they are both allowed to be "absent" (holding no value), but neither may ever contain null
. Holder
in particular seems like it could work for the scenario in your example, since you don't show it being initialized with any value (it isn't given any String
when it's created, so it must initially be absent). Its set
method throws NullPointerException
if given null
, just like you want.
final Holder<String> stringHolder = Holder.absent(); // nothing at first
public void mutate(String arg) {
stringHolder.set(arg);
}
When using a Holder
or Optional
, you should generally check that it isPresent()
before calling get()
since it'll throw IllegalStateException
if absent. Alternatively you can use the or
method:
String definitelyNotNull = stringHolder.or("default");