View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  
23  package org.opencastproject.util;
24  
25  import org.checkerframework.checker.units.qual.A;
26  
27  import java.lang.reflect.InvocationTargetException;
28  import java.lang.reflect.Method;
29  import java.util.Optional;
30  import java.util.function.Function;
31  
32  /**
33   * Enum utility methods.
34   */
35  public final class EnumSupport {
36  
37    private EnumSupport() {
38    }
39  
40    /**
41     * Support method to help enums implement an enhanced <code>valueOf(String)</code> method, that does not throw an
42     * IllegalArgumentException in case of incoming values, that do not match any of the enum's values.
43     *
44     * @param enumClass
45     *          the enum's class
46     * @param value
47     *          the value to look up
48     * @return the matching enum value or null if none matches
49     */
50    @SuppressWarnings("unchecked")
51    public static <E extends Enum<?>> E fromString(Class<E> enumClass, String value) {
52      if (value == null) {
53        return null;
54      }
55      value = value.trim();
56      if (value.length() == 0) {
57        return null;
58      }
59      Method m = null;
60      try {
61        m = enumClass.getDeclaredMethod("valueOf", String.class);
62      } catch (NoSuchMethodException ignore) {
63      }
64      try {
65        m.setAccessible(true);
66      } catch (SecurityException ignore) {
67      }
68      try {
69        E enumConstant = (E) m.invoke(null, value);
70        return enumConstant;
71      } catch (IllegalAccessException ignore) {
72      } catch (InvocationTargetException ignore) {
73      }
74      return null;
75    }
76  
77    /** Create a function to parse a string into an Enum value. */
78    public static <A extends Enum<A>> Function<String, Optional<A>> parseEnum(final A e) {
79      return s -> {
80        try {
81          return Optional.of((A) Enum.valueOf(e.getClass(), s));
82        } catch (Exception ex) {
83          return Optional.empty();
84        }
85      };
86    }
87  }