黑马程序员技术交流社区

标题: 序列化异常 [打印本页]

作者: 贾振凯    时间: 2013-4-3 23:41
标题: 序列化异常
本帖最后由 贾振凯 于 2013-4-16 21:39 编辑
  1. public class Person implements Serializable{
  2. private static final long serialVersionUID = 1L;
  3. private static final Person p = new Person("jzk",1);;
  4. private String name;
  5. private int age;

  6. private Person(String name, int age) {
  7. this.name = name;
  8. this.age = age;
  9. }
  10. public static Person getInstance(){
  11. return p;
  12. }
  13. public String getName() {return name;}
  14. public int getAge() { return age;}

  15. private Object writeReplace()throws ObjectStreamException{
  16. return new Dog("旺财"); //此处将序列化的对像用Dog来替换 }

  17. private Object readResolve()throws ObjectStreamException{
  18. return new Person("jkk",2); //此处读取的时候用new Person("jkk",2)来替换读取的对像值
  19. }
  20. }





  21. public class SerializeOperate {
  22. public static void main(String[] args){

  23. ObjectOutputStream oos = null;
  24. ObjectInputStream ois = null;

  25. try {

  26. oos = new ObjectOutputStream(new FileOutputStream("E:\\serialize.txt"));
  27. ois = new ObjectInputStream(new FileInputStream("E:\\serialize.txt"));
  28. oos.writeObject(Person.getInstance());
  29. //根据上面的注释的理解,,,,,,,,,,,,这个地方为什么会报ClassCastException?????????????????////
  30. System.out.println(Person.getInstance()==(Person)ois.readObject());

  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. throw new RuntimeException("序列化异常!");
  34. } catch (ClassNotFoundException e) {
  35. e.printStackTrace();
  36. throw new RuntimeException("反序列化异常!");
  37. }finally{
  38. try {
  39. if(oos != null)
  40. oos.close();
  41. }catch (IOException e) {
  42. throw new RuntimeException("关闭列化流异常!");
  43. }
  44. try {
  45. if(ois != null)
  46. ois.close();
  47. }catch (IOException e) {
  48. throw new RuntimeException("关闭反序列化流异常!");
  49. }
  50. }
  51. }
  52. }
复制代码

作者: 黄玉昆    时间: 2013-4-15 12:55
你的这个代码有问题吧,其中的Dog是哪里来的啊,请写全代码,把问题写清楚,如果没问题了,请将问题分类改为“已解决”,谢谢




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2