如何在Java中获取地图的值类型? [英] How to get value type of a map in Java?

查看:97
本文介绍了如何在Java中获取地图的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

获取java.util.List的泛型类型


我有一个Map,我想从该Map的一个实例中获取T的类型。我该怎么做?



例如。我想做一些事情:

 地图< String,Double> map = new HashMap< String,Double>(); 
...
String vtype = map.getValueType()。getClass()。getName(); //我想在这里获得Double

当然,在这里没有这样的'getValueType()'函数API。

解决方案

无法从实例中获取它,因为在Java泛型中,类型参数仅在编译时可用,而不是在运行时。

这就是所谓的类型擦除。 JLS。


Possible Duplicate:
Get generic type of java.util.List

I have a Map and I want to get the type of T from an instance of that Map. How can I do that?

e.g. I want to do something like:

Map<String, Double> map = new HashMap<String, Double>();
...
String vtype = map.getValueType().getClass().getName(); //I want to get Double here

Of course there's no such 'getValueType()' function in the API.

解决方案

You can't get it from the instance, because in Java generics the type parameter is available only at compile time, not at run time.

This is known as type erasure. A more formal definition is provided in the JLS.

这篇关于如何在Java中获取地图的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆