Java Reflection Enum getEnumValues(Class type)

Here you can find the source of getEnumValues(Class type)

Description

It will parse the given Class as Enum , returns the list of values of given Enum

License

Apache License

Parameter

Parameter Description
type data type
E data type

Exception

Parameter Description
IllegalArgumentException when given type is not an Enum.

Return

of enum name Strings.

Declaration

public static <E> List<String> getEnumValues(Class<E> type) 

Method Source Code

//package com.java2s;
/**//ww w  .j  a v  a2s .c o m
 * Copyright ? 2013 - 2017 WaveMaker, Inc.
 *
 * 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.ArrayList;

import java.util.List;

public class Main {
    /**
     * It will parse the given {@link Class} as {@link Enum}, returns the list of values of given {@link Enum}
     *
     * @param type data type
     * @param <E>  data type
     * @return {@link List} of enum name Strings.
     * @throws IllegalArgumentException when given type is not an {@link Enum}.
     */
    public static <E> List<String> getEnumValues(Class<E> type) {
        if (isEnum(type)) {
            Class<Enum> enumClass = (Class<Enum>) type;
            List<String> values = new ArrayList<>(enumClass.getEnumConstants().length);
            for (Enum anEnum : enumClass.getEnumConstants()) {
                values.add(anEnum.name());
            }
            return values;
        } else {
            throw new IllegalArgumentException("Given type is not a Enum");
        }
    }

    /**
     * @param type data type
     * @return true if type is instance of {@link Enum}
     */
    public static boolean isEnum(Class<?> type) {
        return type.isEnum();
    }
}

Related

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