【问题标题】:Java object serialized without implementing serializable interface未实现可序列化接口的 Java 对象序列化
【发布时间】:2015-04-08 15:54:34
【问题描述】:

我有以下代码。

Animal.java

   public class Animal{
        String name;
        int age;

        public Animal(){
            name="default name";
            age=0;
        }

    }

猫.java

  public class Cat extends Animal{
        int legs;
        public Cat(){
            super();
            this.legs=10;
        }
    }

Test.java

import java.io.*;

public class Test{

    public static void main(String[] args){

        try{
            Cat c1 = new Cat();
            FileOutputStream fileStream = new FileOutputStream("myobjects.ser");
            ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
            objectStream.writeObject(c1);
        }catch(Exception e){
            e.printStackTrace();
        }   

    }
}

此代码可以正常工作。没有抛出异常。我期待一个异常,因为 cat 类没有实现可序列化的接口。

为什么我的代码有效?

【问题讨论】:

  • 我遇到了一个异常。重新编译并重新运行您的代码。
  • 我没有得到任何东西。使用 open-jdk7
  • 我收到 java.io.NotSerializableException。检查好
  • e.printStackTrace() 将它打印到您可能看不到的错误流中。这就是为什么您认为代码会在静默完成时工作。
  • System.out.println(e)

标签: java serialization exception-handling


【解决方案1】:

程序确实抛出了异常,只是你没有找对地方。

e.printStackTrace() 方法打印到 System.err (STDERR) 流,NOT 到标准控制台输出 (STDOUT)。您很可能没有查看正确的流。大多数 IDE 会显示 System.err,但我不能代表你的。

解决方法是调用System.out.println(e.getMessage())。这会将异常消息打印到 STDOUT。如果你想打印堆栈跟踪,你应该调用e.printStackTrace(System.out)

最好找到查看System.err (STDERR) 流的方法,因为典型的System.out 用于正常程序输出,而不是错误。您可以调用System.err.println(e.getMessage()) 获取异常消息,调用e.printStackTrace(System.err) 获取堆栈跟踪。

【讨论】:

  • 我宁愿使用System.out.println(e.getMessage());System.err.println(e.getMessage());。至于堆栈跟踪,e.printStackTrace(System.out); 会打印到 STDOUT,e.printStackTrace(System.err); 会打印到 STDERR
  • 你是对的。写我的答案时有点分心!我稍后会编辑。
  • 我已经编辑了您的答案以包含我的观察结果。希望对你有帮助
【解决方案2】:

首先,您不应该捕获“异常”。不好的做法。

其次,如果要“查看”异常,让 main() 方法抛出 NotSerializableException(使用 throws)。

【讨论】:

  • 这个答案不正确...(第一句话是,但这并没有回答问题)
猜你喜欢
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多