How to find an object of class Java generic type?

Suppose I have a generic type Pthat is 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 result in a compilation error because it is P.classnot valid. So what can I do to make the above code work?

+3
source share
4 answers

You should have a runtime instance of this generic type somewhere, so that you can just grab the declaration class Enum#getDeclaringClass(). Assuming you declared P psomewhere as an argument to a method, here is an example.

eg.

public static <P extends Enum<P>> P valueOf(P p, String name) {
    return Enum.valueOf(p.getDeclaringClass(), name);
}
+4
source

Java . Object . ( "P" ) , .

.

+3

Java , - . , . , .

+1

, - . , Spring - .

class Converter<P extends Enum> {
    private Class<P> type;

    //setter and getter

    public P valueOf(String name) {
        return Enum.valueOf(type, name);
    }
}

, .

0

Source: https://habr.com/ru/post/1747545/


All Articles