泛型方法的 Java 泛型
我想知道是否可以编写一个方法来处理未定义类型的转换,例如:
前提条件:
Map<String, Object> map = new HashMap<>();
List<String> l = List.of("value");
map.put("key", l);
方法调用:
List<String> strings = convert("key", List.class, String.class);
转换方法本身:
public <V, C extends Collection<V>> C<V> getCollection(String key, Class<C> collType, Class<V> objectType) {
return (C<V>) map.get(key);
}
但是语句C< V>无法编译并给出错误:类型“C”没有类型参数。
有什么想法吗?
I wonder if it is possible to write a method that will handle casting of undefined types like:
Precondition:
Map<String, Object> map = new HashMap<>();
List<String> l = List.of("value");
map.put("key", l);
Method call:
List<String> strings = convert("key", List.class, String.class);
convert method itself:
public <V, C extends Collection<V>> C<V> getCollection(String key, Class<C> collType, Class<V> objectType) {
return (C<V>) map.get(key);
}
But statement C< V > doesn't compile and gives me an error: Type 'C' doesn't have type parameters.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Java 在类型推断中使用目标类型,这意味着可以利用赋值右侧的预期类型来实现此目的。
但是,要利用它,需要进行未经检查的强制转换:
然后您可以从映射中获取类型化条目:
但是,由于 Java 泛型的类型擦除,因此在运行时不会检查类型参数。因此,虽然这会抛出
ClassCastException
:这将在没有任何抱怨的情况下执行,并且在尝试从列表中提取值之前,您不会得到
ClassCastException
:Java uses target typing in type inference which means the expected type on the right-hand side of an assignment can be leveraged for this purpose.
However, to take advantage of it an unchecked cast is needed:
You could then get the typed entry out of the map:
However, because of type erasure of Java generics, the type parameter is not checked at runtime. So while this will throw a
ClassCastException
:This will execute without any complaint, and you won't get a
ClassCastException
until you try to extract the values from the list: