在java中的HashMap中获取变量类型
我有一个HashMap
并存储了3种不同类型的数据(Integer,String,Long)。
如何找出具有特定键的值的类型?
您可以调用getClass
方法来查找对象的类型:
map.get(key).getClass()
将它包装在自定义类(如标记的联合)中可能更好
class Union{ public static enum WrappedType{STRING,INT,LONG;} WrappedType type; String str; int integer; long l; public Union(String str){ type = WrappedType.STRING; this.str=str; } //... }
这是更清洁,你可以肯定你得到了什么
如果要根据类型进行处理。
Object o = map.getKey(key); if (o instanceof Integer) { .. }
您还可以在一些智能类中封装值或映射。
通常不必要地使用Object
类型。 但是根据你的情况,你可能必须有一个HashMap
,尽管最好避免使用它。 也就是说,如果你必须使用一个,这里有一小段代码,可能会有所帮助。 它使用instanceof
。
Map map = new HashMap(); for (Map.Entry e : map.entrySet()) { if (e.getValue() instanceof Integer) { // Do Integer things } else if (e.getValue() instanceof String) { // Do String things } else if (e.getValue() instanceof Long) { // Do Long things } else { // Do other thing, probably want error or print statement } }
您可能会重新考虑将同一集合中的不同类型混为一谈。 你失去了generics的自动类型检查。
否则,您将需要使用instanceof或SLaks建议使用getClass来查找类型。
假设您将对结果执行某些操作,您可以尝试使用instanceof
运算符:
if (yourmap.get(yourkey) instanceof Integer) { // your code for Integer here }