尝试从数组writeObject时不可序列化的异常

时间:2013-04-13 04:45:46

标签: java exception

我在运行试图将对象写入.dat文件的应用程序文件时收到NotSerializableException。

    try{
        Person[] personList = new Person[3];
        personList[0] = new TeamLeader(8, "Mike Johnson", 29);
        personList[1] = new Engineer(0.4,"Russell Sanders", 22);
        personList[2] = new Engineer(0.7, "Steven Peterson", 25);
        out = new ObjectOutputStream(new FileOutputStream("persons.dat"));
        for(int i = 0; i < personList.length; i++) {
            out.writeObject(personList[i]);//error line 85
        }
        //out.writeObject(personList);
    }

    catch(IOException e) {
        System.out.println("Problem writing file");
        e.printStackTrace();
    } 

错误

java.io.NotSerializableException: TeamLeader
     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java: 346)
     at CharlieBrownP6.main(CharlieBrownP6.java: 85)

错误继续为同一错误写入中止

1 个答案:

答案 0 :(得分:2)

调用writeObject的对象必须实现Serializable接口(reference)。