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