D-Klotz
D-Klotz

Reputation: 2073

How do I access the values of any known enum at run-time when passed a String value for the enumeration?

I need to write a service level api that exposes any enumeration at run-time. The name of the enum will be passed as a string parameter to the service layer. So that means I need to use reflection.

All of the answers I've found so far deal with knowing ahead of time the name of the enumeration.

  1. I will have a string that holds the name of the enum.
  2. Look up the enum using reflection (somehow).
  3. Return string representations of the values associated with the enum

Upvotes: 0

Views: 70

Answers (2)

Fabienr_75
Fabienr_75

Reputation: 559

You can use this :

    public static <E extends Enum<E>> List<E> getValues(final String className) throws ClassNotFoundException {
        List<E> lst = null;
        if(className != null) {
            Class<E> clazz = Class.forName(className);
            E[] enumConstants = (E[]) clazz.getEnumConstants();
            lst = Arrays.asList(enumConstants);                
        }
        return lst;
    }

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170158

Try something like this:

package demo;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) throws Exception {

        // ClassNotFoundException thrown when demo.Color does not exist
        Class<?> enumType = Class.forName("demo.Color");

        // constants is null when demo.Color is not an enum
        Object[] constants = enumType.getEnumConstants();

        System.out.println("is " + enumType + " an enum? " + enumType.isEnum());
        System.out.println(Arrays.toString(constants));
    }
}

enum Color {
    GREEN,
    BLUE
}

Upvotes: 1

Related Questions