Closed GoogleCodeExporter closed 9 years ago
Can you describe the code path that would lead to nulls being passed to
Enums.getIfPresent in the first place? Most of Guava's utilities are fairly
strict about nulls in this same way, and this is commonly regarded as a good
thing.
Original comment by wasserman.louis
on 23 Jan 2014 at 4:08
The actual code I'm working on is retrieving a string from an XML document. I
have some code in place now that converts that string into an enum, or returns
a default but thought I'd use the Enums.getIfPresent instead. Its possible
(not likely, but possible) for this string to be null. I changed the code to
use Enums.getIfPresent and tripped a NPE when I ran some tests. I've since
reverted back to the original code. With the null check in the getIfPresent
method, its not as useful. Given that null isn't a valid enum value, it seems
that it should just return Optional.absent() if value is ever null.
Original comment by craig.skinfill
on 23 Jan 2014 at 4:19
As Louis mentioned, nearly all APIs in Guava will throw a NPE on null input. If
you know you're dealing with null, how about:
import static com.google.common.base.Strings.nullToEmpty;
Enums.getIfPresent(enumClass, nullToEmpty(value))
Original comment by kak@google.com
on 23 Jan 2014 at 5:05
Yes the nullToEmpty would work (i had forgotten about that one). But I still
feel that passing null for the value should just result in returning
Optional.absent(), it doesn't seem to hurt anything and makes this method
easier and more useful to work with.
Original comment by craig.skinfill
on 23 Jan 2014 at 5:11
Or with firstNonNull:
import static com.google.common.base.Objects.firstNonNull;
Enums.getIfPresent(MyEnum.class, firstNonNull(value, "SOME_DEFAULT_ENUM"))
Or with a ternary:
return ((value == null) ? Optional.<MyEnum>absent() :
Enums.getIfPresent(MyEnum.class, value)).or(MyEnum.SOME_DEFAULT_ENUM);
Original comment by kak@google.com
on 23 Jan 2014 at 6:14
This issue has been migrated to GitHub.
It can be found at https://github.com/google/guava/issues/<issue id>
Original comment by cgdecker@google.com
on 1 Nov 2014 at 4:10
Original comment by cgdecker@google.com
on 3 Nov 2014 at 9:07
Original issue reported on code.google.com by
craig.skinfill
on 23 Jan 2014 at 4:05