Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullsafe Long valueOf

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

like image 539
0x45 Avatar asked Apr 18 '18 08:04

0x45


People also ask

What is the use of long valueOf in Java?

Java.lang.Long.valueOf () is a built-in method in Java of lang class that returns a Long object holding the value extracted from a specified String S when parsed with the radix that is given in the second argument.

What is the difference between valueOf () and valueOf (null) methods?

As the javadoc explains, String.valueOf ( (Object) null) will be treated as a special case by the valueOf method and the value "null" is returned. By contrast, null.toString () will just give you an NPE. It turns out that String.valueOf (null) (note the difference!) does give an NPE ... despite the javadoc. The real explanation 1 is obscure:

Is it safe to use object to string with null instance?

Also, in the case of Object#toString, if the instance is null, a NullPointerException will be thrown, so arguably, it's less safe.

What is the difference between valueOf() and valueOf in long class?

The valueOf () method of Long class returns a Long object holding the specified long value. The second method returns a Long object holding the specified String value. The third syntax returns a Long object which represents the specified String when parsed with the given radix.


2 Answers

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.

like image 130
Ehler Avatar answered Sep 28 '22 16:09

Ehler


Long.valueOf(null) will throw NumberFormatException, not NullPointerException.

In Java 8, you have the possibility to declaratively choose a default evaluation for a nullable inline, e.g.

Long.valueOf(
    Optional.ofNullable(criteriaIdentifier).orElseGet(() -> "-1")
)

It's a little verbose, but will allow you to default to -1l if criteriaIdentifier is null (no need for additional dependencies).

API here and here.

like image 27
Mena Avatar answered Sep 28 '22 14:09

Mena