[英]How to pass generic list class as an argument to generic method in Java?
I want to have a method which would return required type of objects extracted from a map. 我想要一种方法,该方法将返回从地图提取的所需对象类型。 Here is an example
这是一个例子
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);
}
Then, for example, Integer can be gotten with this code 然后,例如,可以使用此代码获得Integer
Integer id = get("id", Integer.class);
But when I'm trying to get a list of objects in these ways 但是当我试图通过这些方式获取对象列表时
List<Integer> ids = get("ids", new ArrayList<Integer>().getClass());
List<Integer> ids = get("id", List.class);
Intellij IDEA warns: Unchecked assignment: 'java.util.ArrayList' to 'java.util.List<java.lang.Integer>'
Intellij IDEA警告:
Unchecked assignment: 'java.util.ArrayList' to 'java.util.List<java.lang.Integer>'
I expected something like List<Integer>.class
(by analogy to Integer.class
, Boolean.class
etc...) what would be used as 我期望像
List<Integer>.class
这样的东西(类似于Integer.class
, Boolean.class
等...)将用作
List<Integer> ids = get("ids", List<Integer>.class`)
but this is not compiled. 但这尚未编译。
So is there a solution? 那么有解决方案吗?
You don't actually need the Class
parameter. 您实际上不需要
Class
参数。
<T> T unsafeGet(String arg) {
return (T) map.get(arg);
}
I renamed the method, because you're throwing away all compiler type-checking . 我重命名了该方法,因为您将丢弃所有编译器类型检查 。
These two lines compile, but fail at runtime: 这两行可以编译,但是在运行时会失败:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.