注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

让一切都逝去吧

排骨炖泥菜/猪肝炒苹果/鱼籽狗肉汤/狗头薏米汤

 
 
 

日志

 
 

java.io.NotSerializableException: java.util.HashMap$KeySet  

2012-10-25 15:51:33|  分类: Java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
      ejb调用的时候出现这个错,原因是Map的一些方法返回的set不能序列化,具体说明这里有:
package test;  
import java.io.*; 
import java.util.*;  
public class MapCollectionsSerializeMain {      
  private static void trySerialize (Object o) {         
  try {             
    ObjectOutputStream stream  = new ObjectOutputStream(new ByteArrayOutputStream());            
    System.out.print("Trying to serialize " + o + "...");             
    stream.writeObject(o);             
    stream.flush();             
    System.out.println("done");
  }         
  catch (Exception e) {
    System.out.print("failed: ");
    e.printStackTrace();
  }
}
     // ----------------------------------------------------------------------
     // Entry point
    public static void main (String[] args) {
         Map map = new HashMap();
         map.put("one", "one");
         map.put("two", "two");
         map.put("three", "three");
         System.out.println("keySet():");
         trySerialize(map.keySet());
         System.out.println("entrySet():");
         trySerialize(map.entrySet());
         System.out.println("values():");
         trySerialize(map.values());
      }
 }

For the keySet() and valueSet() cases, one could create a new HashSet from those sets, but that's inefficient and it doesn't cover the values() case.  The right answer in the first place is presumably that any Serializable object which contains a Set (or other abstract type not documented as Serializable) must implement its own readObject and writeObject methods which (de-)serialize the set manually.  Either that, or define the object to contain a HashSet (or other type documented as Serializable).

Comments 
The results of keySet(), entrySet() and values() are only views onto the collection and are not serializable independently. The view collections are intentionally not serializable.  Serializing collection views has very strange semantics. The underlying collection would likely have to be serialized as well, but would then be inaccessible when de-serialized? This is an odd and probably bad situation.

      比如,有个方法接收set类型参数,调用时候是这样:
aMethod(..., aMap.keySet());
      当需要序列化再反序列化的时候,也就是我那个ejb调用的时候这样的情况,就出错了。解决方法是这样:
aMethod(..., new HashSet(aMap.keySet()));
      如以上文档说的,这种方式是低效的,正确的解决方式是让所有可能序列化的类都支持序列化,还要实现
readObject、writeObject方法等等。
  评论这张
 
阅读(2301)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017