zhengwen6300 opened a new issue, #817: URL: https://github.com/apache/fesod/issues/817
### Search before asking - [x] I searched in the [issues](https://github.com/apache/fesod/issues) and found nothing similar. ### Motivation 实现枚举的通用转换,一个枚举转化器适用所有枚举(继承同一个接口,属性一样) ### Solution 参照springmvc参数转换接口,org.springframework.core.convert.converter.ConverterFactory和org.springframework.core.convert.converter.Converter ` @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private ObjectMapper objectMapper; @Override public void addFormatters(FormatterRegistry registry) { registry.addConverterFactory(new StringToIEnumConverterFactory()); } } @Slf4j public class StringToIEnumConverterFactory implements ConverterFactory<String, IEnum> { @Override public <T extends IEnum> Converter<String, T> getConverter(Class<T> targetType) { return new StringToIEnumConverter(targetType); } private class StringToIEnumConverter<T extends IEnum> implements Converter<String, T> { private final Class<T> enumType; public StringToIEnumConverter(Class<T> enumType) { this.enumType = enumType; } @Override public T convert(String source) { if (StrUtil.isBlank(source)) { return null; } T result; try { ParameterizedType parameterizedType = (ParameterizedType) enumType.getGenericInterfaces()[0]; Class actualTypeArgument = (Class) parameterizedType.getActualTypeArguments()[0]; Method getEnumByValueMethod = enumType.getMethod("getEnumByValue", actualTypeArgument); Object args = source; if (StrUtil.equals(actualTypeArgument.getName(), Integer.class.getName())) { args = Integer.valueOf(source); } result = (T) getEnumByValueMethod.invoke(null, args); } catch (Exception e) { log.error("字符串转IEnum枚举发生异常", e); return null; } return result; } } } ` ### Alternatives _No response_ ### Anything else? _No response_ ### Are you willing to submit a PR? - [ ] I'm willing to submit a PR! -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
