我想要一种方法,该方法将返回从地图提取的所需对象类型。这是一个例子
Map<String,Object> map = new HashMap<>();
map.put("ids", Arrays.asList(5,345,45645));
map.put("id", 325);
<T> T get(String arg, Class<T> clazz) {
return (T) map.get(arg);
}
然后,例如,可以使用此代码获得Integer
Integer id = get("id", Integer.class);
但是当我尝试通过这些方式获取对象列表时
List<Integer> ids = get("ids", new ArrayList<Integer>().getClass());
List<Integer> ids = get("id", List.class);
Intellij IDEA警告: Unchecked assignment: 'java.util.ArrayList' to 'java.util.List<java.lang.Integer>'
我期望有类似的东西List<Integer>.class
(类似于Integer.class
,Boolean.class
等等。。。)
List<Integer> ids = get("ids", List<Integer>.class`)
但这尚未编译。
那么有解决方案吗?
您实际上不需要Class
参数。
<T> T unsafeGet(String arg) {
return (T) map.get(arg);
}
我重命名了该方法,因为您将丢弃所有编译器类型检查。
这两行可以编译,但是在运行时会失败:
Integer ids = unsafeGet("ids"); // java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.lang.Integer
Element id = unsafeGet("id"); // java.lang.ClassCastException: java.lang.Integer cannot be cast to org.w3c.dom.Element
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句