本文介绍了如何在Java中获取地图的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Map,我想从该Map的一个实例中获取T的类型。我该怎么做?
例如。我想做一些事情:
地图< String,Double> map = new HashMap< String,Double>();
...
String vtype = map.getValueType()。getClass()。getName(); //我想在这里获得Double
当然,在这里没有这样的'getValueType()'函数API。
解决方案
无法从实例中获取它,因为在Java泛型中,类型参数仅在编译时可用,而不是在运行时。
这就是所谓的类型擦除。在
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中获取地图的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!