Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring to get the value of an Enum

Tags:

java

enums

spring

<bean id="xyz" class="com.abc" >
  <property name="name">
    <bean         
            class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
        <property name="staticField" value="com.abc.staticname" />
     </bean>
   </property>
</bean>

This is the way previously I used to set the name of class com.abc. Now, the names should come from another enum. How do I access the enum value to set the name property of my class com.abc?

like image 229
Shamik Avatar asked Nov 09 '10 19:11

Shamik


People also ask

How do you find the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do I get the enum value in Thymeleaf?

Select element using Enum As you can call any java methods within thymeleaf expressions, It is easier to get all the enum values for Role using the Role. values() method as shown below. As the values() method return an array, It is really easy to iterate through then using th:each as shown below.

Which method is used in Java to get the values of an enum?

The Java compiler internally adds the values() method when it creates an enum. The values() method returns an array containing all the values of the enum.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


1 Answers

I don't see why you can't keep on using FieldRetrievingFactoryBean, that's what it's for.

It's a little bit easier to use than your example suggests, though. Also, there's the easier schema-based syntax which does the same thing, <util:constant>.

Both approaches are documented (and compared) here.

(Remember that enum values are just static fields on the enum class)

like image 133
skaffman Avatar answered Oct 09 '22 19:10

skaffman