3

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.

2
  • Why do you need to use reflection? Is Data.MyTypes.valueOf(text) enough for you or you need reflection for a reason you didn't tell us? You can get that with reflection too. You might need it if, for example, the enum class name is a parameter too. Commented Jun 21, 2011 at 8:55
  • Look at this answer, it is exactly what you and I wanted.. stackoverflow.com/a/3735968/2881350 Commented Sep 11, 2014 at 7:04

4 Answers 4

5

Do you mean?

String text = 
MyType myType = MyType.valueOf(text);
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

1

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

Take a look at this.

2 Comments

This is good if the type is dynamic. If you know the type you want, you can use MyEnum.valueOf(String)
Correct, saw reflection so I thought the enum type was dynamic as well. +1 to your answer.
0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.