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
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.
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:
Also, in the case of Object#toString, if the instance is null, a NullPointerException will be thrown, so arguably, it's less safe.
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.
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.
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.
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