Does Guava provide a method to get a default value if a passed object reference is null
? I'am looking for something like <T> T nullToDefault(T obj, T default)
, were the default is returned if obj is null
.
Here on stackoverflow I found nothing about it. I am only looking for a pure Guava solution (if there is some)!
I found nothing in the Gauva 10 API, only com.google.common.base.Objects
looks promising but lacks something similar.
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.
Reference Variable value: Any reference variable in Java has a default value null.
null means that some column is empty/has no value, while default value gives a column some value when we don't set it directly in query.
In additon to Objects.firstNonNull
, Guava 10.0 added the Optional class as a more general solution to this type of problem.
An Optional
is something that may or may not contain a value. There are various ways of creating an Optional
instance, but for your case the factory method Optional.fromNullable(T)
is appropriate.
Once you have an Optional
, you can use one of the or
methods to get the value the Optional
contains (if it contains a value) or some other value (if it does not).
Putting it all together, your simple example would look like:
T value = Optional.fromNullable(obj).or(defaultValue);
The extra flexibility of Optional
comes in if you want to use a Supplier
for the default value (so you don't do the calculation to get it unless necessary) or if you want to chain multiple optional values together to get the first value that is present, for example:
T value = someOptional.or(someOtherOptional).or(someDefault);
How about
MoreObjects.firstNonNull(obj, default)
See the JavaDoc.
(Historical note: the MoreObjects
class used to be called Objects
, but it got renamed to avoid confusion with the java.util.Objects
class introduced in Java 7. The Guava Objects
class is now effectively deprecated.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With