piotrek
piotrek

Reputation: 14540

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?

Upvotes: 3

Views: 737

Answers (1)

jqno
jqno

Reputation: 15520

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! :)

Upvotes: 2

Related Questions