StringToEnumConverter extends AbstractConverter { @SuppressWarnings("unchecked") @Override public Object convert(Object source, TypeToken<?> targetTypeToken) { if (!canHandle(source, targetTypeToken)) throw new ConverterException(source, targetTypeToken.getRawType()); Class enumClass = targetTypeToken.getRawType(); for (Object enumConstant : enumClass.getEnumConstants()) { String enumStr = enumConstant.toString().replaceAll("\\_", ""); String sourceStr = ((String) source).replaceAll("\\-", "").replaceAll("\\_", "").replaceAll("\\s", ""); if (enumStr.equalsIgnoreCase(sourceStr)) { return Enum.valueOf(enumClass, enumConstant.toString()); } } throw new ConverterException(source, targetTypeToken.getRawType(), "can not find enum constants"); }  @SuppressWarnings("unchecked") @Override Object convert(Object source, TypeToken<?> targetTypeToken); @Override boolean canHandle(Object source, TypeToken<?> targetTypeToken);  }
@Test public void testConvert() { assertEquals(TestEnum.CONVERTER, converter.convert("CONVERTER", TypeToken.of(TestEnum.class))); assertEquals(TestEnum.CONVERTER, converter.convert("converter", TypeToken.of(TestEnum.class))); assertEquals(TestEnum.SCRIPT_PROCESSOR, converter.convert("SCRIPT_PROCESSOR", TypeToken.of(TestEnum.class))); assertEquals(TestEnum.SCRIPT_PROCESSOR, converter.convert("script processor", TypeToken.of(TestEnum.class))); assertEquals(TestEnum.SCRIPT_PROCESSOR, converter.convert("script-processor", TypeToken.of(TestEnum.class))); }