Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading