简体   繁体   中英

How to find the class object of Java generic type?

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 declared P p somewhere as a method argument, here's an example.

Eg

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

There is no way in Java. Generic types are erased and converted to Object in byte code. The generic type ('P' in your case) is not a real class but just a placeholder.

Have a look at this question with great answers on type erasure.

Java implements generics using something called type erasure. What that means is the actual generic parameter is erased at runtime. Thus, you cannot infer type information from generic type parameters.

You can get it at runtime by having the caller or some configuration provider it. For example, you could have Spring or whatever configure this.

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

    //setter and getter

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

And then configure it wherever it's needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM