枚举到类对象转换

时间:2012-01-11 09:54:36

标签: java spring enums

我得到枚举值作为输入,每个枚举值对应一个类。 如何定义弹簧配置,给定枚举值应转换为类对象

public enum R {
eR1,
eR2,
eR3;
}

//simple interface
interface R {
    dosomething();
}

//R1 class
class R1 implements R {
    dosomething() {
    //implmentation for R1
    }
}

//R2 class
class R2 implements R {
    dosomething() {
        //implementation for R2
    }
}

我有API说,

getR(R er1) {
   //How do I define spring configuration to get class object given enum value??
}

I want to avoid if conditions in API, something like this
getR(R er) {
    if(er.equals(R.eR1)) {
        //do this
    } else if(er.equals(R.eR2)) {
       //do this
    }
}
I want to spring to inject right class based on input parameter so that I can avoid if statement.

对于三个enum字段,我想避免在春天有三个id。

Can I define somethign like this
<bean id="r" class="com.myProject.R1">
    <property name="er1" value="eR1"/>
</bean>
<bean id="r" class="com.myProject.R2">
    <property name="er2" value="eR2"/>
</bean>
//similary for R3 as well

1 个答案:

答案 0 :(得分:1)

在弹簧配置中,只需使用枚举值

如果你想在R2中注入eR2,

示例

 <bean id="r2" class="com.myProject.R2">
     <property name="er2" value="eR2"/>
 </bean>

查看示例here。您无需使用完全限定名称。请参阅How assign bean's property an Enum value in Spring config file?上的讨论。