Java EnumSet Create fromString(Class enumClass, String name)

Here you can find the source of fromString(Class enumClass, String name)

Description

Parses an Enum of type T case insensitively.

License

Apache License

Parameter

Parameter Description
enumClass the class of the Enum type
name the string to parse
T the type of the Enum class, should be inferred by enumClass

Return

the parse Enum value of type

Declaration

public static <T extends Enum<T>> T fromString(Class<T> enumClass, String name) 

Method Source Code

//package com.java2s;
/**//from w w  w .  jav a2 s.c  om
 * Copyright Microsoft Corporation
 *
 * 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.0
 *
 * 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.
 */

import java.util.EnumSet;

public class Main {
    /**
     * Parses an Enum of type {@link T} case insensitively.
     *
     * @param enumClass the class of the Enum type
     * @param name the string to parse
     * @param <T> the type of the Enum class, should be inferred by enumClass
     * @return the parse Enum value of type {@link T}
     */
    public static <T extends Enum<T>> T fromString(Class<T> enumClass, String name) {
        if (name == null) {
            return null;
        }

        EnumSet<T> values = EnumSet.allOf(enumClass);
        for (T value : values) {
            if (value.name().equalsIgnoreCase(name)) {
                return value;
            }
        }

        // name could also be a numeric value
        int index = Integer.parseInt(name);
        if (index < values.size() && index >= 0) {
            return (T) values.toArray()[index];
        }

        throw new IllegalArgumentException("No enum constant " + enumClass.getCanonicalName() + "." + name);
    }
}

Related

  1. createEnumSet(Class elementType)
  2. enumFromSet(EnumSet theSet)
  3. enumSet(T... elements)
  4. enumSetOf(long bitSet, Class eClass)
  5. fromString(Class enumType, String value)
  6. intToEnumSet(Class enumClass, int decoded)
  7. newEnumSet(Class klass)
  8. noneOf( Class elementType)
  9. of(E e1, E... e)