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