private static <R extends Named> NamedLookup<R> parseConstants(Class<R> enumType, Class<?> constantsType) { Field[] fields = constantsType.getDeclaredFields(); Map<String, R> instances = new HashMap<>(); for (Field field : fields) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && enumType.isAssignableFrom(field.getType())) { if (Modifier.isPublic(constantsType.getModifiers()) == false) { field.setAccessible(true); } try { R instance = enumType.cast(field.get(null)); instances.putIfAbsent(instance.getName(), instance); instances.putIfAbsent(instance.getName().toUpperCase(Locale.ENGLISH), instance); } catch (Exception ex) { throw new IllegalArgumentException("Unable to query field: " + field, ex); } } } ImmutableMap<String, R> constants = ImmutableMap.copyOf(instances); return new NamedLookup<R>() { @Override public ImmutableMap<String, R> lookupAll() { return constants; } }; }
/** * Looks up the external name given a standard enum instance. * <p> * This searches the map of external names and returns the first matching entry * that maps to the given standard name. * * @param namedEnum the named enum to find an external name for * @return the external name * @throws IllegalArgumentException if there is no external name */ public String reverseLookup(T namedEnum) { String name = namedEnum.getName(); for (Entry<String, String> entry : externalNames.entrySet()) { if (entry.getValue().equals(name)) { return entry.getKey(); } } throw new IllegalArgumentException(Messages.format( "{}:{} external name not found for standard name: {}", extendedEnum.type.getSimpleName(), group, name)); }
/** * Returns the map of known instances by normalized name. * <p> * This method returns all known instances, keyed by the normalized name. * This is equivalent to the result of {@link #lookupAll()} adjusted such * that each entry is keyed by the result of {@link Named#getName()}. * * @return the map of enum instance by name */ public ImmutableMap<String, T> lookupAllNormalized() { // add values that are keyed under the normalized name // keep values keyed under a non-normalized name Map<String, T> result = new HashMap<>(); Map<String, T> others = new HashMap<>(); for (Entry<String, T> entry : lookupAll().entrySet()) { String normalizedName = entry.getValue().getName(); if (entry.getKey().equals(normalizedName)) { result.put(normalizedName, entry.getValue()); } else { others.put(normalizedName, entry.getValue()); } } // include any values that are only keyed under a non-normalized name others.values().forEach(v -> result.putIfAbsent(v.getName(), v)); return ImmutableMap.copyOf(result); }