[Java] optional.orElseGet(null) produces a null pointer exception


(Jérémie Bresson) #1

In java when you are working with Optional and you want to pass the value where Optional is not supported you do value = optional.orElse(null). This way if the value is present you have it, if the value is absent you have null.
This is the contrary of optional = Optional.ofNullable(value)

The Optional API has also a orElseGet(..) method that uses a Supplier as argument. The difference is not clear to everybody:

The point is, if you are confusing orElse(..) and orElseGet(..), you will use optional.orElseGet(null) in your code. Its compiles but you get a NullPointerException at runtime.

(Alexandre Gigleux) #4

Hello Jérémie,

Thanks for having raised this case. My suggestion is to enhance the rule S2259: Null pointers should not be dereferenced so that it raises an issue on Optional.orElseGet(null).

Here is the related ticket: https://jira.sonarsource.com/browse/SONARJAVA-2916