001/* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.base; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtCompatible; 020import com.google.common.annotations.GwtIncompatible; 021import java.io.Serializable; 022import java.lang.ref.WeakReference; 023import java.lang.reflect.Field; 024import java.util.EnumSet; 025import java.util.HashMap; 026import java.util.Map; 027import java.util.WeakHashMap; 028import org.checkerframework.checker.nullness.qual.Nullable; 029 030/** 031 * Utility methods for working with {@link Enum} instances. 032 * 033 * @author Steve McKay 034 * @since 9.0 035 */ 036@GwtCompatible(emulated = true) 037public final class Enums { 038 039 private Enums() {} 040 041 /** 042 * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the {@code 043 * Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use {@code 044 * Enums.getField(Sport.GOLF).getAnnotation(Description.class)}. 045 * 046 * @since 12.0 047 */ 048 @GwtIncompatible // reflection 049 public static Field getField(Enum<?> enumValue) { 050 Class<?> clazz = enumValue.getDeclaringClass(); 051 try { 052 return clazz.getDeclaredField(enumValue.name()); 053 } catch (NoSuchFieldException impossible) { 054 throw new AssertionError(impossible); 055 } 056 } 057 058 059 /** 060 * Returns a {@link Function} that maps an {@link Enum} name to the associated {@code Enum} 061 * constant. The {@code Function} will return {@code null} if the {@code Enum} constant 062 * does not exist. 063 * 064 * @param enumClass the {@link Class} of the {@code Enum} declaring the constant values 065 * @deprecated Use {@link Enums#stringConverter} instead. Note that the string converter has 066 * slightly different behavior: it throws {@link IllegalArgumentException} if the enum 067 * constant does not exist rather than returning {@code null}. It also converts {@code null} 068 * to {@code null} rather than throwing {@link NullPointerException}. This method is 069 * scheduled for removal in Guava 18.0. 070 */ 071 @Deprecated 072 public static <T extends Enum<T>> Function<String, T> valueOfFunction( 073 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(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, {@code 118 * 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 return Platform.getEnumIfPresent(enumClass, value); 126 } 127 128 @GwtIncompatible // java.lang.ref.WeakReference 129 private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>> 130 enumConstantCache = new WeakHashMap<>(); 131 132 @GwtIncompatible // java.lang.ref.WeakReference 133 private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache( 134 Class<T> enumClass) { 135 Map<String, WeakReference<? extends Enum<?>>> result = new HashMap<>(); 136 for (T enumInstance : EnumSet.allOf(enumClass)) { 137 result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance)); 138 } 139 enumConstantCache.put(enumClass, result); 140 return result; 141 } 142 143 @GwtIncompatible // java.lang.ref.WeakReference 144 static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants( 145 Class<T> enumClass) { 146 synchronized (enumConstantCache) { 147 Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass); 148 if (constants == null) { 149 constants = populateCache(enumClass); 150 } 151 return constants; 152 } 153 } 154 155 /** 156 * Returns a converter that converts between strings and {@code enum} values of type {@code 157 * enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The converter 158 * will throw an {@code IllegalArgumentException} if the argument is not the name of any enum 159 * constant in the specified enum. 160 * 161 * @since 16.0 162 */ 163 public static <T extends Enum<T>> Converter<String, T> stringConverter(final Class<T> enumClass) { 164 return new StringConverter<T>(enumClass); 165 } 166 167 private static final class StringConverter<T extends Enum<T>> extends Converter<String, T> 168 implements Serializable { 169 170 private final Class<T> enumClass; 171 172 StringConverter(Class<T> enumClass) { 173 this.enumClass = checkNotNull(enumClass); 174 } 175 176 @Override 177 protected T doForward(String value) { 178 return Enum.valueOf(enumClass, value); 179 } 180 181 @Override 182 protected String doBackward(T enumValue) { 183 return enumValue.name(); 184 } 185 186 @Override 187 public boolean equals(@Nullable Object object) { 188 if (object instanceof StringConverter) { 189 StringConverter<?> that = (StringConverter<?>) object; 190 return this.enumClass.equals(that.enumClass); 191 } 192 return false; 193 } 194 195 @Override 196 public int hashCode() { 197 return enumClass.hashCode(); 198 } 199 200 @Override 201 public String toString() { 202 return "Enums.stringConverter(" + enumClass.getName() + ".class)"; 203 } 204 205 private static final long serialVersionUID = 0L; 206 } 207}