java_enthu
java_enthu

Reputation: 2327

Building Enum from String using reflection

I have a method which takes an Enum. Say method is methodName(MyTypes) where MyTypes is inside another class. Data{ enum MyTypes{ Id, Value.... } }

I want to invoke this method dynamically. To call that I have to build an emum of type MyTypes from the input String. The input String is say for example MyTypes.Value. How to build the enum instance dynamically from this string and pass in the method?

When I am doing method.getGenericParameterType() it returns me something like this [class packagename.Data$MyTypes]

using this 2 things required generic type and string value how to build the enum?

Thanks in advance.

Upvotes: 3

Views: 2041

Answers (4)

Peter Nagy
Peter Nagy

Reputation: 158

Here is what I did:

private static Optional<Object> createEnum(Class<?> enumClass, String enumValue) {
    for (Field field : enumClass.getDeclaredFields()) {
        if (field.isEnumConstant() && field.getName().equals(enumValue)) {
            try {
                Method valueOfMethod = enumClass.getDeclaredMethod("valueOf", String.class);
                return Optional.of(valueOfMethod.invoke(null, enumValue));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                return Optional.empty();
            }
        }
    }
    return Optional.empty();
}

Upvotes: 0

ddewaele
ddewaele

Reputation: 22603

Is there a reason why you want to use reflection ? Is the valueOf method not sufficient ?

Take a look at this.

Upvotes: 1

denis.solonenko
denis.solonenko

Reputation: 11765

Something like that: parse the string to get the class name "MyTypes", then get the actual class object using Class.forName(String), then get the enum value using static Enum.valueOf(Class,String)

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533482

Do you mean?

String text = 
MyType myType = MyType.valueOf(text);

Upvotes: 5

Related Questions