[英]Pass a generic class in method parameter
I have a method which accepts two values and converts it into key-value pair of a map and returns it to the calling method.我有一个方法,它接受两个值并将其转换为 map 的键值对并将其返回给调用方法。 The key is always String but the value can be of any Class.键始终是字符串,但值可以是任何 Class。 I can't seem to convert the value into generic while accepting in method signature.在接受方法签名时,我似乎无法将值转换为泛型。 Here's my code:这是我的代码:
private Map<String, Class<T>> mapBuilder(String key, T value) {
Map<String, Class <T>> map = new HashMap<>();
map.put(key, value);
return map;
}
Can someone tell what can be done instead?有人可以告诉我们可以做什么吗?
The Class
is too much. Class
太多了。 T
already refers to the type: T
已经指的是类型:
private <T> Map<String, T> mapBuilder(String key, T value) {
Map<String, T> map = new HashMap<>();
map.put(key, value);
return map;
}
Class<T>
would refer to the class-object of T
Class<T>
将引用T
的类对象
Are you sure you want to have a map with Class
as a value?您确定要使用 map 和Class
作为值吗? If so, you have firstly define a generic type parameter <T>
either at the class level ( public class MyClass <T> {... }
or at the method level:如果是这样,您首先在 class 级别( public class MyClass <T> {... }
或在方法级别定义了一个泛型类型参数<T>
:
private <T> Map<String, Class<T>> mapBuilder(String key, T value) {
Map<String, Class <T>> map = new HashMap<>();
map.put(key, (Class<T>) value.getClass());
return map;
}
Note the following:请注意以下事项:
Class<T>
to the map as a value, you have to get it from the T
object.只要您想将Class<T>
的实例作为值添加到 map 中,您必须从T
object 中获取它。getClass
returns Class<?>
, so an explicit casting is needed (also in the snippet above).只要getClass
返回Class<?>
,类型不兼容就会出现问题,因此需要显式转换(也在上面的代码段中)。Finally, I'd prefer a solution with the wildcard parameter:最后,我更喜欢带有通配符参数的解决方案:
private Map<String, Class<?>> mapBuilder(String key, T value) {
Map<String, Class <?>> map = new HashMap<>();
map.put(key, value.getClass());
return map;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.