001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtIncompatible;
020import com.google.common.annotations.J2ktIncompatible;
021import java.io.Serializable;
022import java.lang.ref.WeakReference;
023import java.lang.reflect.Field;
024import java.util.EnumSet;
025import java.util.HashMap;
026import java.util.Map;
027import java.util.WeakHashMap;
028import org.checkerframework.checker.nullness.qual.Nullable;
029
030/**
031 * Utility methods for working with {@link Enum} instances.
032 *
033 * @author Steve McKay
034 * @since 9.0
035 */
036@GwtIncompatible
037@J2ktIncompatible
038public final class Enums {
039
040  private Enums() {}
041
042  /**
043   * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the {@code
044   * Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use {@code
045   * Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
046   *
047   * @since 12.0
048   */
049  @GwtIncompatible // reflection
050  public static Field getField(Enum<?> enumValue) {
051    Class<?>
052        clazz = enumValue.getDeclaringClass();
053    try {
054      return clazz.getDeclaredField(enumValue.name());
055    } catch (NoSuchFieldException impossible) {
056      throw new AssertionError(impossible);
057    }
058  }
059
060  /**
061   * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
062   * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
063   * user input or falling back to a default enum constant. For example, {@code
064   * Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
065   *
066   * @since 12.0
067   */
068  public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
069    checkNotNull(enumClass);
070    checkNotNull(value);
071    return Platform.getEnumIfPresent(enumClass, value);
072  }
073
074  @GwtIncompatible // java.lang.ref.WeakReference
075  private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>
076      enumConstantCache = new WeakHashMap<>();
077
078  @GwtIncompatible // java.lang.ref.WeakReference
079  private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache(
080      Class<T> enumClass) {
081    Map<String, WeakReference<? extends Enum<?>>> result = new HashMap<>();
082    for (T enumInstance : EnumSet.allOf(enumClass)) {
083      result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance));
084    }
085    enumConstantCache.put(enumClass, result);
086    return result;
087  }
088
089  @GwtIncompatible // java.lang.ref.WeakReference
090  static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
091      Class<T> enumClass) {
092    synchronized (enumConstantCache) {
093      Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass);
094      if (constants == null) {
095        constants = populateCache(enumClass);
096      }
097      return constants;
098    }
099  }
100
101  /**
102   * Returns a serializable converter that converts between strings and {@code enum} values of type
103   * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The
104   * converter will throw an {@code IllegalArgumentException} if the argument is not the name of any
105   * enum constant in the specified enum.
106   *
107   * @since 16.0
108   */
109  @GwtIncompatible
110  public static <T extends Enum<T>> Converter<String, T> stringConverter(Class<T> enumClass) {
111    return new StringConverter<>(enumClass);
112  }
113
114  @GwtIncompatible
115  private static final class StringConverter<T extends Enum<T>> extends Converter<String, T>
116      implements Serializable {
117
118    private final Class<T> enumClass;
119
120    StringConverter(Class<T> enumClass) {
121      this.enumClass = checkNotNull(enumClass);
122    }
123
124    @Override
125    protected T doForward(String value) {
126      return Enum.valueOf(enumClass, value);
127    }
128
129    @Override
130    protected String doBackward(T enumValue) {
131      return enumValue.name();
132    }
133
134    @Override
135    public boolean equals(@Nullable Object object) {
136      if (object instanceof StringConverter) {
137        StringConverter<?> that = (StringConverter<?>) object;
138        return this.enumClass.equals(that.enumClass);
139      }
140      return false;
141    }
142
143    @Override
144    public int hashCode() {
145      return enumClass.hashCode();
146    }
147
148    @Override
149    public String toString() {
150      return "Enums.stringConverter(" + enumClass.getName() + ".class)";
151    }
152
153    private static final long serialVersionUID = 0L;
154  }
155}