开发者

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 a开发者_StackOverflowm 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.


Do you mean?

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


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)


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

Take a look at this.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜