Java泛型:声明泛型类型的映射值 [英] Java generics: Declare map value of generic type
问题描述
拥有 Map
类似于
private static Map< String,Object>地图;
以及像
public< T> T getObject(final Class< T> myClass){
return(T)map.get(myClass);
如何更改地图声明以便不必在执行转换时返回的方法?
您需要制作一个泛型类,而不是泛型方法:
public class MyClass< T> {
私人地图< String,T>地图;
public T getObject(final String key){
return map.get(key);
$ / code $ / pre
另外,我将参数从Class更改为串。如果map.get()需要一个String,那么传递一个类没有任何意义。
编辑:我没有注意到map是静态的。如果您可以将其更改为非静态而不破坏程序的其他部分,则可以使用此功能。如果你不能,那么你不能避免演员。
I am new to generics.
Having a Map
like
private static Map<String, Object> map;
and a method like
public <T> T getObject(final Class<T> myClass) {
return (T)map.get(myClass);
}
How to change the map declaration in order to not have to do the cast when returning from the method ?
解决方案 You would need to make a generic class, not a generic method:
public class MyClass<T> {
private Map<String, T> map;
public T getObject(final String key) {
return map.get(key);
}
}
Also, I changed the parameter from a Class to a String. It doesn't make sense to pass a Class if map.get() expects a String.
Edit: I didn't notice that map was static. If you can change it to non-static without it breaking other parts of your program, this could work. If you can't, then you cannot avoid a cast.
这篇关于Java泛型:声明泛型类型的映射值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!