Java String Value Of valueOf(Class enumType, String constantName)

Here you can find the source of valueOf(Class enumType, String constantName)

Description

This works like Enum#valueOf(Class,String) but returns null if constant wasn't found instead of throwing an IllegalArgumentException.

License

Apache License

Parameter

Parameter Description
enumType Enumeration class
constantName name of the constant

Return

the matching constant or null if not found

Declaration

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String constantName) 

Method Source Code

//package com.java2s;
/*--------------------------------------------------------------------------+
   $Id: EnumUtils.java 16749 2008-06-20 16:04:47Z deissenb $
 |                                                                          |
 | Copyright 2005-2008 Technische Universitaet Muenchen                     |
 |                                                                          |
 | Licensed under the Apache License, Version 2.0 (the "License");          |
 | you may not use this file except in compliance with the License.         |
 | You may obtain a copy of the License at                                  |
 |                                                                          |
 |    http://www.apache.org/licenses/LICENSE-2.                        |
 |                                                                          |
 | Unless required by applicable law or agreed to in writing, software      |
 | distributed under the License is distributed on an "AS IS" BASIS,        |
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
 | See the License for the specific language governing permissions and      |
 | limitations under the License.                                           |
 +--------------------------------------------------------------------------*/

public class Main {
    /**/*from  w  w w .java 2  s  .  c  o m*/
     * This works like {@link Enum#valueOf(Class, String)}
     * but returns <code>null</code> if constant wasn't found instead of
     * throwing an <code>IllegalArgumentException</code>.
     * 
     * @param enumType
     *            Enumeration class
     * @param constantName
     *            name of the constant
     * @return the matching constant or <code>null</code> if not found
     */
    public static <T extends Enum<T>> T valueOf(Class<T> enumType, String constantName) {
        try {
            T constant = Enum.valueOf(enumType, constantName);
            return constant;
        } catch (IllegalArgumentException ex) {
            return null;
        }
    }
}

Related

  1. valueOf(Class cls, String s)
  2. valueOf(Class en, String name)
  3. valueOf(Class enumType, String name)
  4. valueOf(Class enumType, String name)
  5. valueOf(Class enumType, String name)
  6. valueOf(Class enumType, String name, T defaultValue)