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.

java_enthu
  • 2,279
  • 7
  • 44
  • 74
  • 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. – aalku Jun 21 '11 at 08:55
  • Look at this answer, it is exactly what you and I wanted.. http://stackoverflow.com/a/3735968/2881350 – Karl.S Sep 11 '14 at 07:04

4 Answers4

5

Do you mean?

String text = 
MyType myType = MyType.valueOf(text);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
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)

denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
1

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

Take a look at this.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
ddewaele
  • 22,363
  • 10
  • 69
  • 82
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();
}
Peter Nagy
  • 86
  • 1
  • 7