Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-safe valueOf method

Tags:

java

I need to convert several String values to Integer,Boolean, etc., however since the input values may be null I can't use the Integer.valueOf() method for example. If the input is null I need the output object to be null as well, so I can't use apache commons NumberUtils.toInt(). Is there an existing implementation or a better solution than just writing a utility method for each type(Integer, Boolean etc.)?

Edit: adding code sample

String maxAgeStr = settings.get("maxAge"); //settings is a map, which may or //may not contain maxAge constraints.setMaxAge(Integer.valueOf(maxAgeStr)); // need null safety here String enableActionStr = settings.get("enableAction"); constraints.setEnableAction(Boolean.valueOf(enableActionStr)); // need null safety here

like image 718
Alex Avatar asked Nov 19 '14 15:11

Alex


People also ask

Is long valueOf null-safe?

It's null-safe and you can optionally specify a default value.

Can string valueOf return null?

The String. valueOf(Object) method, as its Javadoc-generated documentation states, returns "null" if the passed in object is null and returns the results on the passed-in Object 's toString() call if the passed-in Object is not null. In other words, String. valueOf(String) does the null checking for you.

What is null safety in programming?

Void safety (also known as null safety) is a guarantee within an object-oriented programming language that no object references will have null or void values. In object-oriented languages, access to objects is achieved through references (or, equivalently, pointers).

What is the valueOf method?

The valueOf() method returns the primitive value of a string. The valueOf() method does not change the original string. The valueOf() method can be used to convert a string object into a string.


2 Answers

Use commons-lang NumberUtils.createInteger() method:

NumberUtils.createInteger(null); // null
NumberUtils.createInteger("5"); // 5
like image 126
Maciej Walkowiak Avatar answered Sep 16 '22 23:09

Maciej Walkowiak


Touches Java 8:

Optional<String> maxAgeStr = Optional.ofNullable(settings.get("maxAge"));
maxAgeStr.ifPresent((str) -> { constraints.setMaxAge(Integer.valueOf(str)); });

Optional<String> enableActionStr = Optional.ofNullable(settings.get("enableAction"));
constraints.setEnableAction(Boolean.valueOf(enableActionStr.orElse(false))); 

Optional<String> enableActionStr = Optional.ofNullable(settings.get("enableAction"));
constraints.setEnableAction(Boolean.valueOf(enableActionStr.orElseGet(() -> i%2 == 0))); 
like image 27
Joop Eggen Avatar answered Sep 17 '22 23:09

Joop Eggen