• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.base;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtCompatible;
23 import com.google.common.annotations.GwtIncompatible;
24 
25 import java.io.Serializable;
26 import java.lang.ref.WeakReference;
27 import java.lang.reflect.Field;
28 import java.util.EnumSet;
29 import java.util.HashMap;
30 import java.util.Map;
31 import java.util.WeakHashMap;
32 
33 import javax.annotation.Nullable;
34 
35 /**
36  * Utility methods for working with {@link Enum} instances.
37  *
38  * @author Steve McKay
39  *
40  * @since 9.0
41  */
42 @GwtCompatible(emulated = true)
43 @Beta
44 public final class Enums {
45 
Enums()46   private Enums() {}
47 
48   /**
49    * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the
50    * {@code Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use
51    * {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
52    *
53    * @since 12.0
54    */
55   @GwtIncompatible("reflection")
getField(Enum<?> enumValue)56   public static Field getField(Enum<?> enumValue) {
57     Class<?> clazz = enumValue.getDeclaringClass();
58     try {
59       return clazz.getDeclaredField(enumValue.name());
60     } catch (NoSuchFieldException impossible) {
61       throw new AssertionError(impossible);
62     }
63   }
64 
65   /**
66    * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
67    * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
68    * user input or falling back to a default enum constant. For example,
69    * {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
70    *
71    * @since 12.0
72    */
getIfPresent( Class<T> enumClass, String value)73   public static <T extends Enum<T>> Optional<T> getIfPresent(
74       Class<T> enumClass, String value) {
75     checkNotNull(enumClass);
76     checkNotNull(value);
77     return Platform.getEnumIfPresent(enumClass, value);
78   }
79 
80   @GwtIncompatible("java.lang.ref.WeakReference")
81   private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>
82       enumConstantCache = new WeakHashMap
83               <Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>>();
84 
85   @GwtIncompatible("java.lang.ref.WeakReference")
populateCache( Class<T> enumClass)86   private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache(
87       Class<T> enumClass) {
88     Map<String, WeakReference<? extends Enum<?>>> result
89         = new HashMap<String, WeakReference<? extends Enum<?>>>();
90     for (T enumInstance : EnumSet.allOf(enumClass)) {
91       result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance));
92     }
93     enumConstantCache.put(enumClass, result);
94     return result;
95   }
96 
97   @GwtIncompatible("java.lang.ref.WeakReference")
getEnumConstants( Class<T> enumClass)98   static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants(
99       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    */
stringConverter(final Class<T> enumClass)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 
StringConverter(Class<T> enumClass)127     StringConverter(Class<T> enumClass) {
128       this.enumClass = checkNotNull(enumClass);
129     }
130 
131     @Override
doForward(String value)132     protected T doForward(String value) {
133       return Enum.valueOf(enumClass, value);
134     }
135 
136     @Override
doBackward(T enumValue)137     protected String doBackward(T enumValue) {
138       return enumValue.name();
139     }
140 
141     @Override
equals(@ullable Object object)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
hashCode()151     public int hashCode() {
152       return enumClass.hashCode();
153     }
154 
155     @Override
toString()156     public String toString() {
157       return "Enums.stringConverter(" + enumClass.getName() + ".class)";
158     }
159 
160     private static final long serialVersionUID = 0L;
161   }
162 }
163