/** as {@link #valueOfIgnoreCase(String, Enum[], String)} for all values of the given enum and using the enum type as the message */ public static <T extends Enum<?>> Maybe<T> valueOfIgnoreCase(Class<T> type, String givenValue) { return valueOfIgnoreCase(JavaClassNames.simpleClassName(type), values(type), givenValue); }
/** as {@link #checkAllEnumeratedIgnoreCase(String, Enum[], String...)} using the same default strategy * that {@link #valueOfIgnoreCase(Class, String)} applies */ public static void checkAllEnumeratedIgnoreCase(Class<? extends Enum<?>> type, String ...explicitValues) { checkAllEnumeratedIgnoreCase(JavaClassNames.simpleClassName(type), values(type), explicitValues); } /** checks that all accepted enum values are represented by the given set of explicit values */
public static <E extends Enum<E>> Maybe<E> tryCoerce(String input, Class<E> targetType) { if (input==null) return null; if (targetType==null) return Maybe.absent("Null enum type"); if (!targetType.isEnum()) return Maybe.absent("Type '"+targetType+"' is not an enum"); List<String> options = ImmutableList.of( input, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, input), CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, input), CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input), CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input)); for (String value : options) { try { return Maybe.of(Enum.valueOf(targetType, value)); } catch (IllegalArgumentException iae) { continue; } } Maybe<E> result = Enums.valueOfIgnoreCase(targetType, input); if (result.isPresent()) return result; return Maybe.absent(new ClassCoercionException("Invalid value '"+input+"' for "+JavaClassNames.simpleClassName(targetType)+"; expected one of "+ Arrays.asList(Enums.values(targetType)))); }