Created
February 5, 2018 20:19
-
-
Save jandk/f3356c8a2eac97a37878c9beac3824e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component | |
@Order(Ordered.HIGHEST_PRECEDENCE) | |
@SuppressWarnings({"unchecked", "rawtypes"}) | |
static final class StringToEnumConverterFactory implements ConverterFactory<String, Enum> { | |
@Override | |
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) { | |
return new StringToEnum(getEnumType(targetType)); | |
} | |
private static Class<?> getEnumType(Class<?> 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 enumType; | |
} | |
private class StringToEnum<T extends Enum> implements Converter<String, T> { | |
private final Class<T> enumType; | |
StringToEnum(Class<T> enumType) { | |
this.enumType = enumType; | |
} | |
@Override | |
public T convert(String source) { | |
if (source.isEmpty()) { | |
return null; | |
} | |
return (T) Enum.valueOf(this.enumType, source.trim().toUpperCase()); | |
} | |
} | |
} | |
@Configuration | |
static class WebMvcConfigurer extends WebMvcConfigurerAdapter { | |
@Override | |
public void addFormatters(FormatterRegistry registry) { | |
registry.removeConvertible(String.class, Enum.class); | |
registry.addConverterFactory(new StringToEnumConverterFactory()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment