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
It's null-safe and you can optionally specify a default value.
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.
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).
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.
Use commons-lang
NumberUtils.createInteger() method:
NumberUtils.createInteger(null); // null
NumberUtils.createInteger("5"); // 5
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)));
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