【问题标题】:java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entryjava.lang.ClassCastException:java.util.HashMap$EntrySet 无法转换为 java.util.Map$Entry
【发布时间】:2015-08-05 12:18:58
【问题描述】:

我有一个这样的重写方法

@Override
public Build auth (Map.Entry<String, String> auth) {
            this.mAuth = auth;
            return this;
}

这里我尝试通过以下方式调用这个方法

Map<String, String> authentication = new HashMap<String , String> ();        
         authentication.put("username" , "testname");
         authentication.put("password" , "testpassword");        

Map.Entry<String, String> authInfo =(Entry<String , String>) authentication.entrySet();

AuthMethod.auth(authInfo)

在运行时得到

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entry

如何将Map.Entry&lt;String, String&gt; 传递给身份验证方法

【问题讨论】:

  • 单个条目不是一组条目...您为什么期望可以工作? (你控制 API 吗?接受 Map.Entry&lt;String, String&gt; 作为参数而不是两个字符串真的很奇怪......)

标签: java dictionary


【解决方案1】:

您正在尝试将集合转换为单个条目。

您可以通过迭代集合来使用每个条目项:

Iterator it = authentication.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry entry = (Map.Entry)it.next(); //current entry in a loop
    /*
     * do something for each entry
     */
}

【讨论】:

    【解决方案2】:

    嗯,是的。

    您正在尝试将Set&lt;Map.Entry&lt;String, String&gt;&gt; 转换为单个Map.Entry&lt;String, String&gt;

    您需要在集合中选择一个元素,或者迭代每个条目并对其进行处理。

    以下内容:

    for (Map.Entry<String, String> entry: authentication.entrySet()) {
        // TODO logic with single entry
    }
    

    【讨论】:

      【解决方案3】:
      Map.Entry<String, String> authInfo =(Entry<String, String>) authentication.entrySet();
      

      在这里你做错了演员。您提到的身份验证方法似乎只需要用户名/密码对的值。所以像下面这样的事情会做:

      Map<String, String> authentication = new HashMap<String, String>();         
      authentication.put("testname", "testpassword");
      Map.Entry<String, String> authInfo = authentication.entrySet().iterator().next();
      AuthMethod.auth(authInfo)
      

      【讨论】:

        【解决方案4】:

        authentication.entrySet()Entry 的集合。你可以像这样处理它们:

           authentication.entrySet().stream().map(x->auth(x)).collect(Collectors.toList())
        

        【讨论】:

        • 您可能想指定您的答案仅是 Java 8。
        【解决方案5】:

        如果我们想返回一个特定的 Entry(row),我们需要通过 iterator.next() 迭代第一个条目:

        Map.Entry<String, String> authInfo = (Entry<String, String>)   
        authentication.entrySet().iterator().next();
        

        如果我们想遍历地图,我们需要保持这样的循环:

        for( Map.Entry<String, String> authInfo : authentication.entrySet()){
            System.out.println("authInfo:"+authInfo.getKey());
        }
        

        【讨论】:

          【解决方案6】:

          下面的函数可以作为通用迭代、设置、获取地图值的参考。

          (Iterator<Entry> i = entries.iterator(); i.hasNext(); ) {
              Map.Entry e = (Entry) i.next(); 
              if(((String)e.getValue())==null ){
                  i.remove();
              } else {
                  e.setValue("false");
              }
              System.out.println(e.getValue());
          }
          

          【讨论】:

            【解决方案7】:

            我终于设法做到了,但是用一种很笨拙的方式,我真的不明白为什么它这么复杂

            package utils;
            
            import java.io.IOException;
            import java.lang.reflect.Field;
            import java.util.List;
            import java.util.Map;
            
            import com.fasterxml.jackson.core.JsonParser;
            import com.fasterxml.jackson.core.JsonProcessingException;
            import com.fasterxml.jackson.core.type.TypeReference;
            import com.fasterxml.jackson.databind.DeserializationContext;
            import com.fasterxml.jackson.databind.JsonDeserializer;
            import com.fasterxml.jackson.databind.node.ObjectNode;
            import com.fasterxml.jackson.databind.node.TreeTraversingParser;
            
            import models.Product;
            import play.Logger;
            import play.libs.Json;
            
            public class ProductDeserializer extends JsonDeserializer<List<Product>>{
            
            
            @Override
            public List<Product> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            
                Map.Entry<String,ObjectNode> map;
                try {   
            
                TreeTraversingParser parser=(TreeTraversingParser)p;
                Class ftClass = parser.getClass();
                Field nodeCursor = ftClass.getDeclaredField("_nodeCursor");
                boolean nodeCursorAccessible=nodeCursor.isAccessible();
                // Allow modification on the field
                nodeCursor.setAccessible(true);
                Class nodeClass =nodeCursor.get(parser).getClass();
                Field content = nodeClass.getDeclaredField("_current");
                boolean contentAccessible=content.isAccessible();
                content.setAccessible(true);
                map=(Map.Entry<String,ObjectNode>)content.get(nodeCursor.get(parser));
                ObjectNode ob=map.getValue();   
                nodeCursor.setAccessible(nodeCursorAccessible);
                content.setAccessible(contentAccessible);
            
                return Json.mapper().readValue(ob.get("order_rows").traverse(), new TypeReference<List<Product>>(){});
            }catch(Exception e) {
                Logger.error("could not map product for this order"+p.getCurrentValue().toString());
            }
                return null;
            
            }
            
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-09-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-08-04
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多