【问题标题】:Serialization error when using out.writeObject(object)使用 out.writeObject(object) 时出现序列化错误
【发布时间】:2016-06-11 11:12:26
【问题描述】:

我正在研究标记接口的行为,我使用下面的链接制作了自己的标记接口,

Link

然后我在比较 Serializable 接口的功能。

现在我有了不扩展可序列化接口的 Employee 类

public class Employee {

public String name;
public String address;
public int number;
 }

然后我有另一个类 SerializeDemo 尝试序列化对象

public class SerializeDemo {

    public static void main(String [] args)
       {
          Employee e = new Employee();
          e.name = "AAAA";
          e.address = "BBB, India";
          e.number = 101;

          try
          {
             FileOutputStream fileOut =  new FileOutputStream("employee.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
             out.writeObject(e); //Error on this line( ERRORLINE)
             out.close();
             fileOut.close();
             System.out.printf("Serialized data is saved in /tmp/employee.ser");
          }catch(IOException i)
          {
              i.printStackTrace();
          }
       }
}



Error : java.io.NotSerializableException: com.serializable.Employee
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)......

现在,当我删除 ERRORLINE 行时,它会编译并创建一个新文件,但没有对象。 我只是想知道如何 out.writeObject(e);导致错误, ObjectOutputStream 是实现了 Serializable 接口,还是扩展到了其他实现 Serializable 接口的类。

如何out.writeObject(e);内部检查它是否可序列化??

任何帮助将不胜感激!

【问题讨论】:

    标签: java serialization marker-interfaces


    【解决方案1】:

    您要序列化的对象必须标记为 Serializable。

    【讨论】:

    • 我认为你没有理解问题,请仔细阅读,我知道我们需要将它们标记为 Serializable
    • @MandeepSingh 那么为什么你会惊讶于这个异常,因为 Employee 没有实现 Serializable?
    • 我想知道为什么它在内部给出异常,在层次结构中哪个类实现了 Serializable 和 ObjectOutputStream 扩展了哪个类让他知道这种行为
    • ObjectOutputStream 只是做类似if (!(object instanceof Serializable)) throw new NotSerializableException 的事情。您的 Employee 对象没有实现 Serializable,因此会引发异常。 ObjectOutputStream 本身不需要实现或扩展任何东西就可以做到这一点。
    • 不,我不明白你的问题是什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2021-08-16
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多