【问题标题】:Get variable type in a HashMap in java在java中的HashMap中获取变量类型
【发布时间】:2011-12-23 04:44:20
【问题描述】:

我有一个HashMap<String,Object> 并存储了一些来自 3 种不同类型(整数、字符串、长整数)的数据。
如何找出具有特定键的值的类型?

【问题讨论】:

  • 既然您知道期望什么样的对象。见this

标签: java types hashmap


【解决方案1】:

您可以调用getClass method来查找对象的类型:

map.get(key).getClass()

【讨论】:

    【解决方案2】:

    您可能会重新考虑将同一集合中的不同类型混为一谈。你失去了泛型的自动类型检查。

    否则,您需要使用 instanceof 或 SLaks 建议的 getClass 来找出类型。

    【讨论】:

      【解决方案3】:

      将它包装在自定义类中可能会更好(例如标记的联合)

      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;
          }
      
          //...
      }
      

      这样更干净,你可以确定你得到了什么

      【讨论】:

      • 或每种类型的子类型,IFYSWIM。甚至可以添加一些有趣的行为。
      • 取决于他想用它做什么
      【解决方案4】:

      如果要根据类型进行处理。

      Object o = map.getKey(key);
      if (o instanceof Integer) {
      ..
      }
      

      您还可以将值或映射封装在某个智能类中。

      【讨论】:

        【解决方案5】:

        假设你会对结果做点什么,你可以试试instanceof 操作符:

        if (yourmap.get(yourkey) instanceof Integer) {
            // your code for Integer here
        }
        

        【讨论】:

          【解决方案6】:

          通常不赞成不必要地使用Object 类型。但根据您的情况,您可能必须拥有HashMap<String, Object>,但最好避免使用。也就是说,如果您必须使用一个,这里有一小段代码可能会有所帮助。它使用instanceof

              Map<String, Object> map = new HashMap<String, Object>();
          
              for (Map.Entry<String, Object> 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
                  }
              }
          

          【讨论】:

            猜你喜欢
            • 2018-07-30
            • 1970-01-01
            • 2013-09-17
            • 1970-01-01
            • 1970-01-01
            • 2015-07-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多