我想说您正在尝试解决错误的问题。我通常将枚举保留为字符串,从而首先避免这个问题。缺点当然是更大的 DB 字段,但这并不重要。
也就是说:
我会说一般来说这是可能的,但不是以一种干净的方式。我要做的是让所有这些枚举实现一个通用接口(只是一个标记接口或包含int getId() 方法的接口)。现在只为这个接口注册你的 PropertyEditor,这样你就不会破坏太多的标准功能。
然后,您的下一个问题是您依赖于静态工厂方法,这不能以通用方式完成。你的 PropertyEditor 当然可以:
enumClass.getDeclaredMethod("withId", int.class).invoke(id)
但我认为这很 hacky。像这样的东西怎么样:
Object target = null;
for(Object e : EnumSet.allOf(yourEnumClass)){
if(e instanceof MyInterface && ((MyInterface)e).getId()==thisId){
target = e;
break;
}
}
return target;
现在你没有使用任何静态工厂方法,并且你有编译时安全,只要你的枚举实现一个公共接口。
更新:使用新的 Converter SPI 变得更容易。使用a custom ConverterFactory:
public class CustomEnumConverterFactory implements
ConverterFactory<String, Enum<?>>{
@Override
public <T extends Enum<?>> Converter<String, T> getConverter(
final Class<T> targetType){
return WithId.class.isAssignableFrom(targetType)
? new EnumWithIdConverter(targetType)
: new StandardEnumConverter(targetType);
}
}
这样注册:
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<!-- converters is a set of both converters and converterfactories -->
<bean class="foo.bar.CustomEnumConverterFactory" />
</property>
</bean>