kmosley
kmosley

Reputation: 366

Spring: convert a nullable String value to Double

I have a map of strings. I want to pull a value out of that map and pass it into another object as a Double property. It's possible that the key resolves to null. What is the best way to do this?

As an example, this fails when the value resolves to null:

<bean id="someBean" class="mystuff.Example">
    <property name="someDoubleProp">
        <bean class="java.lang.Double">
            <constructor-arg value="#{jobParameters['something']}" />
        </bean>
    </property>
</bean>

I'm hopefully looking for some nice SpEL expression that is the same as this java:

myMap.get("something") == null ? null : new Double(myMap.get("something"))

Upvotes: 1

Views: 629

Answers (1)

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18413

Use ternary operator and static method call

#{jobParameters['something']==null?(double)0:T(java.lang.Double).valueOf(jobParameters['something'])}

be carefull because, if jobParameters['something'] is not rappresenting a valid double you will get a NumberFormatException.
You can think to use a function like NumberUtils.toDouble() that doesn't throw exception, but set a default value.

Upvotes: 1

Related Questions