public class MyIntegerEnumConverters {
@WritingConverter
public static class EnumToIntegerConverter implements Converter<IntEnumConvertable, String> {
@Override
public String convert(IntEnumConvertable source) {
return String.valueOf(source.getValue());
}
}
}
public class MyIntegerToEnumConverterFactory implements ConverterFactory<String, Enum> {
@Override
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
Class<?> enumType = targetType;
while (enumType != null && !enumType.isEnum()) {
enumType = enumType.getSuperclass();
}
if (enumType == null) {
throw new IllegalArgumentException(
"The target type " + targetType.getName() + " does not refer to an enum");
}
return new IntegerToEnum(enumType);
}
@ReadingConverter
public static class IntegerToEnum<T extends IntEnumConvertable> implements Converter<String, IntEnumConvertable> {
private final Class<T> enumType;
public IntegerToEnum(Class<T> enumType) {
this.enumType = enumType;
}
@Override
public IntEnumConvertable convert(String source) {
for (T t : enumType.getEnumConstants()) {
if (t instanceof IntEnumConvertable) {
if (t.getValue() == Integer.valueOf(source)) {
return t;
}
}
}
return null;
}
}
}
public interface IntEnumConvertable extends Serializable {
int getValue();
}
registry.addConverter(new MyIntegerEnumConverters.EnumToIntegerConverter());
registry.addConverter(new MyIntegerToEnumConverterFactory.IntegerToEnum(null));
registry.addConverterFactory(new MyIntegerToEnumConverterFactory());