Nullsafe Long valueOf

0x45 picture 0x45 · Apr 18, 2018 · Viewed 11.6k times · Source

Imagine the following scenario Long critId = Long.valueOf(criteriaIdentifier);

If the view is initially loaded criteriaIdentifier may be null, afterwards I set the value depending of the selectedItem in the JSF View.

However, Long.valueOf(criteriaIdentifier) throws a NumberFormatException - If the string cannot be parsed as a long(i.e null).

I've thought of default setting the Id to default -1, but I wanted to know if there is better practice .

PS: technically the criteriaIdentifier can't be -1, since these values are set from the Database, with a Sequence Generator, so I should know -1 was the default value and properly do the default operations

Answer

Ehler picture Ehler · Apr 18, 2018

You can use the NumberUtils from Apache Commons. It's null-safe and you can optionally specify a default value.

Example:

NumberUtils.toLong(null) = 0L
NumberUtils.toLong("")   = 0L
NumberUtils.toLong("1")  = 1L

NumberUtils.toLong(null, 1L) = 1L
NumberUtils.toLong("", 1L)   = 1L
NumberUtils.toLong("1", 0L)  = 1L

For more info, check the API.