gpt4 book ai didi

java - 所有枚举的 Spring 自定义转换器

转载 作者:IT老高 更新时间:2023-10-28 13:52:51 28 4
gpt4 key购买 nike

我已经使用 int getID()MyEnum withID(int) 方法构建了许多 Enum 类,这些方法允许我将 ID 专用于枚举值以实现持久性(从而避免由于枚举外部存储的顺序/名称更改而导致的更改)。

我想构建一个自定义转换器,它会进行一些反射以查找这些方法,并在找不到它们时使用它们或备份到 Ordinal/String 转换。

任何人都可以使用通用枚举转换器吗?这只是我第二次涉足 Converters。

最佳答案

我想说您正在尝试解决错误的问题。我通常将枚举保留为字符串,从而首先避免这个问题。缺点当然是更大的 DB 字段,但这并不重要。


也就是说:

我会说一般来说这是可能的,但不是以一种干净的方式。我要做的是让所有这些枚举实现一个通用接口(interface)(只是一个标记接口(interface)或一个包含 int getId() 方法的接口(interface))。现在只为这个接口(interface)注册你的 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;

现在您没有使用任何静态工厂方法,并且您具有编译时安全性,只要您的枚举实现一个通用接口(interface)。


更新:使用新的 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>

关于java - 所有枚举的 Spring 自定义转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5178622/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com