【问题标题】:java serialization working unexpectedly?java序列化意外工作?
【发布时间】:2013-09-16 20:25:04
【问题描述】:

嗨,如果一个类不能实现可序列化接口,如果我们尝试序列化它,我们应该得到一个NotSerializableException. 我没有得到它。 Cat 类没有实现 Serializable,我尝试对其进行序列化。为什么编译运行正常?

 import java.io.*;
 class Cat{}
 class MyTest{
 public static void main(String a[]){
    Cat c = new Cat();
    try{
        FileOutputStream fos = new FileOutputStream("test.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(c);
        oos.close();
        fos.close();
    }
    catch(Exception e){e.getMessage();}
    try{
        FileInputStream fis = new FileInputStream("test.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c =  (Cat)ois.readObject();
        ois.close();
        fis.close();
    }
    catch(Exception e){e.getMessage();}
}
}

【问题讨论】:

  • 你怎么知道你没有收到错误
  • 没错。使用该代码,您无法知道。

标签: java serialization


【解决方案1】:

这是在抛出异常,你只是在吞下它们

catch(Exception e){e.getMessage();}

它只是调用一个返回字符串的方法,它不记录任何东西。

使用

e.printStackTrace();

【讨论】:

  • 找到了这个stackoverflow.com/questions/7469316/…....还有其他方法吗?
  • @JNL 当然。 Exception 的方法为您提供了各种选择:获取错误消息,获取堆栈跟踪,您可以覆盖或添加并使用您自己的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2017-09-27
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
相关资源
最近更新 更多