Convert Class <capture of ?> to Class <T>

I have an object which I am using reflection to create the Class object.

I am trying to convert an Enum field to its valueOf, but I do not know what Enum class it is.

Currently, I am just checking if the object is each Enum like this:

Class<?> t = obj.getType();

if (t == MyEnumA.class) {
   value = MyEnumA.valueOf(v)
} else if (t == MyEnumB.class) {
   value = MyEnumB.valueOf(v)
} else if ...

I currently have several different Enum classes, and as I add more I have to add a new else-if block for that new Enum.

I want to use something like this:

if (t.isEmun()) {
   value = Enum.valueOf(t, v);

But I have an error:

Required type: Class<T>
Provided type: Class<capture of ?>

How do I convert my Class<capture of ?> to Class<T>?

>Solution :

You can use asSubclass() to safely cast:

value = Enum.valueOf(t.asSubclass(Enum.class), v);

Leave a Reply