/** * scan. * * @param basePackage base package * @param type type to find * @param <T> enum type * @return found */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T extends Enum<T> & DiscoverableEnum<T>> DiscoverableEnums<T> discoverableEnums( // final String basePackage, final Class<?> type // ) { return new DiscoverableEnums(basePackage, type); } }
/** * parse enum. * * @param targetType targetType * @param source text or name * @return enum instance */ public Optional<T> parse(final Class<T> targetType, final String source) { final String textOrName = source.trim().toUpperCase(); final Optional<T> result = this.parseByText(targetType, textOrName); return result.isPresent() ? result : this.parseByName(targetType, textOrName); }
private DiscoverableEnums(final String basePackage, final Class<T> type) { final Set<Class<T>> discoverableEnums = scanDiscoverableEnums(basePackage, type); final Map<Class<?>, Map<String, T>> typeToText2ConstantMap = newLinkedHashMap(); final Map<String, T> text2ConstantAllInOneMap = newLinkedHashMap(); final Map<String, Collection<String>> discoverableEnumTexts = newLinkedHashMap(); discoverableEnums.forEach(discoverableEnum -> { final Map<String, T> text2ConstantMap = text2ConstantMap(discoverableEnum); typeToText2ConstantMap.put(discoverableEnum, text2ConstantMap); text2ConstantMap.entrySet().forEach(entry -> { final String text = entry.getKey(); final T constant = entry.getValue(); if (text2ConstantAllInOneMap.containsKey(text)) { throw new IllegalArgumentException("'" + text + "' of '" + constant + "' conflict with '" + text + "' of '" + text2ConstantAllInOneMap.get(text).getDeclaringClass() + "'"); } text2ConstantAllInOneMap.put(text, constant); }); discoverableEnumTexts.put(StringUtils.lowerCaseFirstChar(discoverableEnum.getSimpleName()), ImmutableList.copyOf(enumTexts(discoverableEnum))); }); this.type2TextConstantMap = ImmutableMap.copyOf(typeToText2ConstantMap); this.allTextConstantMap = ImmutableMap.copyOf(text2ConstantAllInOneMap); }
/** * for String2DiscoverableEnumConverter. * * @param source text or name * @param targetType targetType * @return enum instance */ @SuppressWarnings("unchecked") public Object convert(final Object source, final TypeDescriptor targetType) { final Object result; if (source != null) { result = this.parse((Class<T>) targetType.getType(), source.toString()); } else { result = null; } return result; }