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.Nullable;
034
035/**
036 * Utility methods for working with {@link Enum} instances.
037 *
038 * @author Steve McKay
039 *
040 * @since 9.0
041 */
042@GwtCompatible(emulated = true)
043@Beta
044public final class Enums {
045
046  private Enums() {}
047
048  /**
049   * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the
050   * {@code Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use
051   * {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
052   *
053   * @since 12.0
054   */
055  @GwtIncompatible("reflection")
056  public static Field getField(Enum<?> enumValue) {
057    Class<?> clazz = enumValue.getDeclaringClass();
058    try {
059      return clazz.getDeclaredField(enumValue.name());
060    } catch (NoSuchFieldException impossible) {
061      throw new AssertionError(impossible);
062    }
063  }
064
065  /**
066   * Returns a {@link Function} that maps an {@link Enum} name to the associated {@code Enum}
067   * constant. The {@code Function} will return {@code null} if the {@code Enum} constant
068   * does not exist.
069   *
070   * @param enumClass the {@link Class} of the {@code Enum} declaring the constant values
071   * @deprecated Use {@link Enums#stringConverter} instead. Note that the string converter has
072   *     slightly different behavior: it throws {@link IllegalArgumentException} if the enum
073   *     constant does not exist rather than returning {@code null}. It also converts {@code null}
074   *     to {@code null} rather than throwing {@link NullPointerException}. This method is
075   *     scheduled for removal in Guava 18.0.
076   */
077  @Deprecated
078  public static <T extends Enum<T>> Function<String, T> valueOfFunction(
079      Class<T> enumClass) {
080    return new ValueOfFunction<T>(enumClass);
081  }
082
083  /**
084   * A {@link Function} that maps an {@link Enum} name to the associated constant, or {@code null}
085   * if the constant does not exist.
086   */
087  private static final class ValueOfFunction<T extends Enum<T>>
088      implements Function<String, T>, Serializable {
089
090    private final Class<T> enumClass;
091
092    private ValueOfFunction(Class<T> enumClass) {
093      this.enumClass = checkNotNull(enumClass);
094    }
095
096    @Override
097    public T apply(String value) {
098      try {
099        return Enum.valueOf(enumClass, value);
100      } catch (IllegalArgumentException e) {
101        return null;
102      }
103    }
104
105    @Override public boolean equals(@Nullable Object obj) {
106      return obj instanceof ValueOfFunction && enumClass.equals(((ValueOfFunction) obj).enumClass);
107    }
108
109    @Override public int hashCode() {
110      return enumClass.hashCode();
111    }
112
113    @Override public String toString() {
114      return "Enums.valueOf(" + enumClass + ")";
115    }
116
117    private static final long serialVersionUID = 0;
118  }
119
120  /**
121   * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
122   * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
123   * user input or falling back to a default enum constant. For example,
124   * {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
125   *
126   * @since 12.0
127   */
128  public static <T extends Enum<T>> Optional<T> getIfPresent(
129      Class<T> enumClass, String value) {
130    checkNotNull(enumClass);
131    checkNotNull(value);
132    return Platform.getEnumIfPresent(enumClass, value);
133  }
134
135  @GwtIncompatible("java.lang.ref.WeakReference")
136  private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>
137      enumConstantCache = new WeakHashMap
138              <Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>();
139
140  @GwtIncompatible("java.lang.ref.WeakReference")
141  private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache(
142      Class<T> enumClass) {
143    Map<String, WeakReference<? extends Enum<?>>> result
144        = new HashMap<String, WeakReference<? extends Enum<?>>>();
145    for (T enumInstance : EnumSet.allOf(enumClass)) {
146      result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance));
147    }
148    enumConstantCache.put(enumClass, result);
149    return result;
150  }
151
152  @GwtIncompatible("java.lang.ref.WeakReference")
153  static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
154      Class<T> enumClass) {
155    synchronized (enumConstantCache) {
156      Map<String, WeakReference<? extends Enum<?>>> constants =
157          enumConstantCache.get(enumClass);
158      if (constants == null) {
159        constants = populateCache(enumClass);
160      }
161      return constants;
162    }
163  }
164
165  /**
166   * Returns a converter that converts between strings and {@code enum} values of type
167   * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The
168   * converter will throw an {@code IllegalArgumentException} if the argument is not the name of
169   * any enum constant in the specified enum.
170   *
171   * @since 16.0
172   */
173  public static <T extends Enum<T>> Converter<String, T> stringConverter(final Class<T> enumClass) {
174    return new StringConverter<T>(enumClass);
175  }
176
177  private static final class StringConverter<T extends Enum<T>>
178      extends Converter<String, T> implements Serializable {
179
180    private final Class<T> enumClass;
181
182    StringConverter(Class<T> enumClass) {
183      this.enumClass = checkNotNull(enumClass);
184    }
185
186    @Override
187    protected T doForward(String value) {
188      return Enum.valueOf(enumClass, value);
189    }
190
191    @Override
192    protected String doBackward(T enumValue) {
193      return enumValue.name();
194    }
195
196    @Override
197    public boolean equals(@Nullable Object object) {
198      if (object instanceof StringConverter) {
199        StringConverter<?> that = (StringConverter<?>) object;
200        return this.enumClass.equals(that.enumClass);
201      }
202      return false;
203    }
204
205    @Override
206    public int hashCode() {
207      return enumClass.hashCode();
208    }
209
210    @Override
211    public String toString() {
212      return "Enums.stringConverter(" + enumClass.getName() + ".class)";
213    }
214
215    private static final long serialVersionUID = 0L;
216  }
217}