Assume I have a generic type P which is an Enum, that is <P extends Enum<P>>, and I want to get the Enum value from a string, for example:
String foo = "foo";
P fooEnum = Enum.valueOf(P.class, foo);
This will get a compile error because P.class is invalid. So what can I do in order to make the above code work?
You must have a runtime instance of this generic type somewhere so that you can just grab the declaring class by
Enum#getDeclaringClass(). Assuming that you’ve declaredP psomewhere as a method argument, here’s an example.E.g.