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.GwtCompatible;
020import com.google.common.annotations.GwtIncompatible;
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 javax.annotation.CheckForNull;
029
030/**
031 * Utility methods for working with {@link Enum} instances.
032 *
033 * @author Steve McKay
034 * @since 9.0
035 */
036@GwtCompatible(emulated = true)
037@ElementTypesAreNonnullByDefault
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<?> clazz = enumValue.getDeclaringClass();
052    try {
053      return clazz.getDeclaredField(enumValue.name());
054    } catch (NoSuchFieldException impossible) {
055      throw new AssertionError(impossible);
056    }
057  }
058
059  /**
060   * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
061   * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
062   * user input or falling back to a default enum constant. For example, {@code
063   * Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
064   *
065   * @since 12.0
066   */
067  public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
068    checkNotNull(enumClass);
069    checkNotNull(value);
070    return Platform.getEnumIfPresent(enumClass, value);
071  }
072
073  @GwtIncompatible // java.lang.ref.WeakReference
074  private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>
075      enumConstantCache = new WeakHashMap<>();
076
077  @GwtIncompatible // java.lang.ref.WeakReference
078  private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache(
079      Class<T> enumClass) {
080    Map<String, WeakReference<? extends Enum<?>>> result = new HashMap<>();
081    for (T enumInstance : EnumSet.allOf(enumClass)) {
082      result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance));
083    }
084    enumConstantCache.put(enumClass, result);
085    return result;
086  }
087
088  @GwtIncompatible // java.lang.ref.WeakReference
089  static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
090      Class<T> enumClass) {
091    synchronized (enumConstantCache) {
092      Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass);
093      if (constants == null) {
094        constants = populateCache(enumClass);
095      }
096      return constants;
097    }
098  }
099
100  /**
101   * Returns a converter that converts between strings and {@code enum} values of type {@code
102   * enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The converter
103   * will throw an {@code IllegalArgumentException} if the argument is not the name of any enum
104   * constant in the specified enum.
105   *
106   * @since 16.0
107   */
108  public static <T extends Enum<T>> Converter<String, T> stringConverter(final Class<T> enumClass) {
109    return new StringConverter<T>(enumClass);
110  }
111
112  private static final class StringConverter<T extends Enum<T>> extends Converter<String, T>
113      implements Serializable {
114
115    private final Class<T> enumClass;
116
117    StringConverter(Class<T> enumClass) {
118      this.enumClass = checkNotNull(enumClass);
119    }
120
121    @Override
122    protected T doForward(String value) {
123      return Enum.valueOf(enumClass, value);
124    }
125
126    @Override
127    protected String doBackward(T enumValue) {
128      return enumValue.name();
129    }
130
131    @Override
132    public boolean equals(@CheckForNull Object object) {
133      if (object instanceof StringConverter) {
134        StringConverter<?> that = (StringConverter<?>) object;
135        return this.enumClass.equals(that.enumClass);
136      }
137      return false;
138    }
139
140    @Override
141    public int hashCode() {
142      return enumClass.hashCode();
143    }
144
145    @Override
146    public String toString() {
147      return "Enums.stringConverter(" + enumClass.getName() + ".class)";
148    }
149
150    private static final long serialVersionUID = 0L;
151  }
152}