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    
017    package com.google.common.base;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.Beta;
022    import com.google.common.annotations.GwtCompatible;
023    
024    /**
025     * Utility methods for working with {@link Enum} instances.
026     *
027     * @author smckay@google.com (Steve McKay)
028     *
029     * @since 9
030     */
031    @GwtCompatible
032    @Beta
033    public final class Enums {
034    
035      private Enums() {}
036    
037      /**
038       * Returns a {@link Function} that maps an {@link Enum} name to the associated
039       * {@code Enum} constant. The {@code Function} will return {@code null} if the
040       * {@code Enum} constant does not exist.
041       *
042       * @param enumClass the {@link Class} of the {@code Enum} declaring the
043       *     constant values.
044       */
045      public static <T extends Enum<T>> Function<String, T> valueOfFunction(Class<T> enumClass) {
046        return new ValueOfFunction<T>(enumClass);
047      }
048    
049      /**
050       * {@link Function} that maps an {@link Enum} name to the associated
051       * constant, or {@code null} if the constant does not exist.
052       */
053      private static final class ValueOfFunction<T extends Enum<T>> implements
054          Function<String, T> {
055    
056        private final Class<T> enumClass;
057    
058        private ValueOfFunction(Class<T> enumClass) {
059          this.enumClass = checkNotNull(enumClass);
060        }
061    
062        @Override
063        public T apply(String value) {
064          try {
065            return Enum.valueOf(enumClass, value);
066          } catch (IllegalArgumentException e) {
067            return null;
068          }
069        }
070      }
071    }