Alex
Alex

Reputation: 1131

Null-safe valueOf method

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

Upvotes: 11

Views: 17337

Answers (3)

icza
icza

Reputation: 418067

Your settings object should support getter methods with different return types, for example:

public String getString(String name);

public int getInt(String name);

public boolean getBoolean(String name);

Also for simplicity you can provide a generic get():

public <T> T get(String name);

This way you can do the conversion in one place (in the settings), and all the code that reads and uses the settings will remain type-safe and free of a bunch of conversions. Also this is the place where you can introduce default values, in one central place.

If you don't have many settings, best would be to add direct getter methods for each of them, for example:

public int getMaxAge();

public boolean isEnableAction();

Upvotes: 2

Joop Eggen
Joop Eggen

Reputation: 109597

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))); 

Upvotes: 2

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

Use commons-lang NumberUtils.createInteger() method:

NumberUtils.createInteger(null); // null
NumberUtils.createInteger("5"); // 5

Upvotes: 17

Related Questions