0

I want to implement this generic methode for all my enums , but i can't get the enumType ??

public static <T extends Enum> T getValue(String value) throws ValidationException {
    try {
        Class<T> enumType = null; //i can't get it ????
        return (T) T.valueOf(enumType, value);
    } catch (Exception e) {
        throw new ValidationException(ERROR_CODE.ERR_INVALID_PARAM);
    }
}
4
  • 1
    No, you can't. You have to accept an extra Class<T> parameter. Commented Apr 24, 2020 at 13:57
  • Ok thanks I'll add it like parameter. Commented Apr 24, 2020 at 14:07
  • 1
    @Sweeper but then you may as well just invoke Enum.valueOf(clazz, value) directly. Commented Apr 24, 2020 at 14:08
  • BTW: <T extends Enum<T>> Commented Apr 24, 2020 at 14:09

1 Answer 1

1

Java's generics system uses an approach called "type erasure". This means that the type parameters, such as T, only exist in the source code, not the actual compiled program. As such, there is no way to know what type T represents when the method is called since the whole notion of T doesn't even exist during runtime.

Unfortunately, the only way for the method to get a Class<T> instance is to actually pass it as a parameter:

MyEnum e = getValue(MyEnum.class, "MY_VALUE");

Once you have the Class<T> instance, you can call the getEnumConstants() method on it to get an array of all the enum values. You can then search through it for the value with the desired name:

T[] constants = enumType.getEnumConstants();
for (T c : constants) {
    if (c.name().equals(value)) {
        return c;
    }
}
throw new IllegalArgumentException("No such value: " + value);
Sign up to request clarification or add additional context in comments.

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.