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 an optional enum constant for the given type, using {@link Enum#valueOf}. If the
067   * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
068   * user input or falling back to a default enum constant. For example,
069   * {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
070   *
071   * @since 12.0
072   */
073  public static <T extends Enum<T>> Optional<T> getIfPresent(
074      Class<T> enumClass, String value) {
075    checkNotNull(enumClass);
076    checkNotNull(value);
077    return Platform.getEnumIfPresent(enumClass, value);
078  }
079
080  @GwtIncompatible("java.lang.ref.WeakReference")
081  private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>
082      enumConstantCache = new WeakHashMap
083              <Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>();
084
085  @GwtIncompatible("java.lang.ref.WeakReference")
086  private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache(
087      Class<T> enumClass) {
088    Map<String, WeakReference<? extends Enum<?>>> result
089        = new HashMap<String, WeakReference<? extends Enum<?>>>();
090    for (T enumInstance : EnumSet.allOf(enumClass)) {
091      result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance));
092    }
093    enumConstantCache.put(enumClass, result);
094    return result;
095  }
096
097  @GwtIncompatible("java.lang.ref.WeakReference")
098  static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
099      Class<T> enumClass) {
100    synchronized (enumConstantCache) {
101      Map<String, WeakReference<? extends Enum<?>>> constants =
102          enumConstantCache.get(enumClass);
103      if (constants == null) {
104        constants = populateCache(enumClass);
105      }
106      return constants;
107    }
108  }
109
110  /**
111   * Returns a converter that converts between strings and {@code enum} values of type
112   * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The
113   * converter will throw an {@code IllegalArgumentException} if the argument is not the name of
114   * any enum constant in the specified enum.
115   *
116   * @since 16.0
117   */
118  public static <T extends Enum<T>> Converter<String, T> stringConverter(final Class<T> enumClass) {
119    return new StringConverter<T>(enumClass);
120  }
121
122  private static final class StringConverter<T extends Enum<T>>
123      extends Converter<String, T> implements Serializable {
124
125    private final Class<T> enumClass;
126
127    StringConverter(Class<T> enumClass) {
128      this.enumClass = checkNotNull(enumClass);
129    }
130
131    @Override
132    protected T doForward(String value) {
133      return Enum.valueOf(enumClass, value);
134    }
135
136    @Override
137    protected String doBackward(T enumValue) {
138      return enumValue.name();
139    }
140
141    @Override
142    public boolean equals(@Nullable Object object) {
143      if (object instanceof StringConverter) {
144        StringConverter<?> that = (StringConverter<?>) object;
145        return this.enumClass.equals(that.enumClass);
146      }
147      return false;
148    }
149
150    @Override
151    public int hashCode() {
152      return enumClass.hashCode();
153    }
154
155    @Override
156    public String toString() {
157      return "Enums.stringConverter(" + enumClass.getName() + ".class)";
158    }
159
160    private static final long serialVersionUID = 0L;
161  }
162}