Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generics syntax map.entry

I have a variable:

Class<Map.Entry<String, Boolean>> clazz;

And I want to assign a class to it without instantiating anything. but compiler doesn't let me write:

Class<Map.Entry<String, Boolean>> clazz = Map.Entry<String, Boolean>.class;

how can i do the assignment?

like image 901
piotrek Avatar asked Dec 28 '25 04:12

piotrek


1 Answers

Class<Map.Entry<String, Boolean>> clazz =
    (Class<Map.Entry<String, Boolean>>)(Class<?>)Map.Entry.class;

Ahh, the joys of type erasure.

The Java compiler distinguishes between the types Map.Entry (raw) and Map.Entry<String, Boolean> (parameterized). Unfortunately, you can't add the type parameters in a type literal using .class. So you have to cast. But you can't do this directly; you'll have to take a 'detour' through Class<?>. I don't remember why, exactly, I'm sorry :).

Also, you'll get an 'unchecked' warning, which you can suppress, because you know (in this case) that the cast will always succeed. So:

@SuppressWarnings("unchecked")
Class<Map.Entry<String, Boolean>> clazz =
    (Class<Map.Entry<String, Boolean>>)(Class<?>)Map.Entry.class;

(No need to put the warning on the method where this assignment happens; you can just put it directly in front of the assignment.)

Enjoy! :)

like image 118
jqno Avatar answered Dec 30 '25 17:12

jqno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!