Java Reflection Enum toEnum(Class e, String s)

Here you can find the source of toEnum(Class e, String s)

Description

to Enum

License

Open Source License

Declaration

public static <Type extends Enum<Type>> Type toEnum(Class<Type> e, String s) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-3.0-standalone.html
 ******************************************************************************/

import java.util.ArrayList;

public class Main {
    public static <Type extends Enum<Type>> Type toEnum(Class<Type> e, String s) {
        try {//from  w w  w  .  ja  va 2 s .c om
            return Type.valueOf(e, s);
        } catch (IllegalArgumentException ex) {
            return null;
        } catch (NullPointerException ex) {
            return null;
        }
    }

    public static <Type extends Enum<Type>> ArrayList<Type> toEnum(Class<Type> e, String[] values) {

        ArrayList<Type> enumValues = new ArrayList<Type>();

        for (String value : values) {

            Type enumValue = toEnum(e, value);

            if (enumValue != null) {
                enumValues.add(enumValue);
            }
        }

        if (enumValues.isEmpty()) {
            return null;
        } else {
            return enumValues;
        }
    }

    public static <Type extends Enum<Type>> Type toEnum(Type[] es, int ordinal) {

        for (Type typeValue : es) {

            if (typeValue.ordinal() == ordinal) {

                return typeValue;
            }
        }

        return null;
    }
}

Related

  1. getEnumConstants(Class c)
  2. getEnumNames(Class> e)
  3. getEnumValues(Class type)
  4. getOptionsFromEnum(Class> enumClass)
  5. isLegalEnum(Class clazz, Object enuValue)
  6. toStrings(Class clenum)