英文:
Pass a generic class in method parameter
问题
我有一个方法,接受两个值,并将其转换为地图的键值对,然后将其返回给调用方法。键始终为String,但值可以是任何类。我似乎无法在方法签名中接受转换值为通用类型。这是我的代码:
private Map<String, Class<T>> mapBuilder(String key, T value) {
Map<String, Class<T>> map = new HashMap<>();
map.put(key, value);
return map;
}
有人可以告诉我可以做些什么替代吗?
英文:
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. The key is always String but the value can be of any 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?
答案1
得分: 1
你确定要将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;
}
请注意以下几点:
- 只要你想将
Class<T>
的实例作为值添加到映射中,你需要从T
对象中获取它。 - 由于
getClass
方法返回的是Class<?>
,所以存在类型不兼容的问题,因此需要进行显式类型转换(如上方代码段所示)。
最后,我更倾向于使用通配符参数的解决方案:
private Map<String, Class<?>> mapBuilder(String key, T value) {
Map<String, Class<?>> map = new HashMap<>();
map.put(key, value.getClass());
return map;
}
英文:
Are you sure you want to have a map with Class
as a value? 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:
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:
- As long as you want to add an instance of
Class<T>
to the map as a value, you have to get it from theT
object. - There is a problem with the type incompatibility as long as
getClass
returnsClass<?>
, so an explicit casting is needed (also in the snippet above).
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;
}
答案2
得分: 0
private <T> Map<String, T> mapBuilder(String key, T value) {
Map<String, T> map = new HashMap<>();
map.put(key, value);
return map;
}
Class<T>
将会引用类型 T
的类对象。
英文:
The Class
is too much. T
already refers to the type:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论