Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring, beans and enum's valueOf

When calling Spring's "Validate" from Eclipse, I get a lot of errors when I want to get back an enum using Enum's implicit "valueOf" method.

For example:

<bean id="docFamily" class="...DocFamily" factory-method="valueOf">
    <constructor-arg>
      <value>LOGY</value>
    </constructor-arg>
</bean>

has Eclipse telling me:

Non-static factory method 'valueOf' with 1 arguments not found in factory bean class ...

However as I understand it from the documentation:

BeanWrapperImpl supports JDK 1.5 enums and old-style enum classes: String values will be treated as enum value names

So the above should work right? (btw is 'constructor-arg' the correct tag in that case, shouldn't it be some 'method-arg'?).

Why is Eclipse/Spring's "Validate" giving me that error message?

like image 539
Gugussee Avatar asked Oct 13 '22 17:10

Gugussee


2 Answers

Enum.valueOf() has two arguments:

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)

Therefore the desired definition may look like this:

<bean id="docFamily" class="java.lang.Enum" factory-method="valueOf">
     <constructor-arg index = "0"><value>...DocFamily</value></constructor-arg>
     <constructor-arg index = "1"><value>LOGY</value></constructor-arg>
</bean> 

However, something like this can be a more elegant solution:

<util:constant id = "docFamily" static-field = "...DocFamily.LOGY" />
like image 64
axtavt Avatar answered Oct 24 '22 22:10

axtavt


I just tried using it like this:

<bean id="docFamily" class="...DocFamily" factory-method="valueOf">
    <constructor-arg type="java.lang.String" value="LOGY"/>
</bean>

and it worked like charm. Does it works for you?

like image 28
Chango Avatar answered Oct 25 '22 00:10

Chango