简体   繁体   English

泛型语法map.entry

[英]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? 我怎么做作业?

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). Java编译器区分Map.Entry (raw)和Map.Entry<String, Boolean> (参数化)类型。 Unfortunately, you can't add the type parameters in a type literal using .class . 不幸的是,您无法使用.class在类型文字中添加类型参数。 So you have to cast. 所以你必须施展。 But you can't do this directly; 但你不能直接这样做; you'll have to take a 'detour' through Class<?> . 你必须通过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! 请享用! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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