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.GwtIncompatible; 020import com.google.common.annotations.J2ktIncompatible; 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.jspecify.annotations.Nullable; 029 030/** 031 * Utility methods for working with {@link Enum} instances. 032 * 033 * @author Steve McKay 034 * @since 9.0 035 */ 036@GwtIncompatible 037@J2ktIncompatible 038public final class Enums { 039 040 private Enums() {} 041 042 /** 043 * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the {@code 044 * Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use {@code 045 * Enums.getField(Sport.GOLF).getAnnotation(Description.class)}. 046 * 047 * @since 12.0 048 */ 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 * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the 060 * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing 061 * user input or falling back to a default enum constant. For example, {@code 062 * Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);} 063 * 064 * @since 12.0 065 */ 066 public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) { 067 checkNotNull(enumClass); 068 checkNotNull(value); 069 return Platform.getEnumIfPresent(enumClass, value); 070 } 071 072 private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>> 073 enumConstantCache = new WeakHashMap<>(); 074 075 private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache( 076 Class<T> enumClass) { 077 Map<String, WeakReference<? extends Enum<?>>> result = new HashMap<>(); 078 for (T enumInstance : EnumSet.allOf(enumClass)) { 079 result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance)); 080 } 081 enumConstantCache.put(enumClass, result); 082 return result; 083 } 084 085 static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants( 086 Class<T> enumClass) { 087 synchronized (enumConstantCache) { 088 Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass); 089 if (constants == null) { 090 constants = populateCache(enumClass); 091 } 092 return constants; 093 } 094 } 095 096 /** 097 * Returns a serializable converter that converts between strings and {@code enum} values of type 098 * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The 099 * converter will throw an {@code IllegalArgumentException} if the argument is not the name of any 100 * enum constant in the specified enum. 101 * 102 * @since 16.0 103 */ 104 public static <T extends Enum<T>> Converter<String, T> stringConverter(Class<T> enumClass) { 105 return new StringConverter<>(enumClass); 106 } 107 108 private static final class StringConverter<T extends Enum<T>> extends Converter<String, T> 109 implements Serializable { 110 111 private final Class<T> enumClass; 112 113 StringConverter(Class<T> enumClass) { 114 this.enumClass = checkNotNull(enumClass); 115 } 116 117 @Override 118 protected T doForward(String value) { 119 return Enum.valueOf(enumClass, value); 120 } 121 122 @Override 123 protected String doBackward(T enumValue) { 124 return enumValue.name(); 125 } 126 127 @Override 128 public boolean equals(@Nullable Object obj) { 129 if (obj instanceof StringConverter) { 130 StringConverter<?> that = (StringConverter<?>) obj; 131 return this.enumClass.equals(that.enumClass); 132 } 133 return false; 134 } 135 136 @Override 137 public int hashCode() { 138 return enumClass.hashCode(); 139 } 140 141 @Override 142 public String toString() { 143 return "Enums.stringConverter(" + enumClass.getName() + ".class)"; 144 } 145 146 private static final long serialVersionUID = 0L; 147 } 148}