很简单的类没有序列化

时间:2016-11-21 13:08:02

标签: java serialization io

我正在使用Object I / O执行并创建了一个非常简单的类(Thing),它只有一个属性(int weight)

我收到了一个notSerializable异常,我真的不明白。

The Thing Class:

import java.io.Serializable;

public class Thing implements Comparable<Thing>, Serializable{

    private static final long serialVersionUID = 1L;
    private int weight;

    public Thing(int weight) {
        this.weight = weight;
    }

    public Thing(){
        this((int)(Math.random()*1000));
    }

    public int getWeight() {
        return weight;
    }

    @Override
    public int compareTo(Thing o) {
        return this.weight - o.weight;
    }
}

My Saver课程:

    public class Saver {

    private FileOutputStream fos;
    private ObjectOutputStream oos;
    private File file;

    public Saver() {
        file = new File("src/dataSaverReader/things.data");
    }

    public void saveArrayToFile(Thing[] array) {
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Thing element : array) {
            try {
                oos.writeObject(element);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            oos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

异常详细信息:

java.io.NotSerializableException: methods.Thing
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at dataSaverReader.Saver.saveArrayToFile(Saver.java:32)
at methods.Root.go(Root.java:48)
at methods.Root.main(Root.java:17)

0 个答案:

没有答案
相关问题