0

我有一个实现 Serializable 的类,但是每当我尝试将其写入磁盘时,我都无法找到为什么它会抛出此异常。我正在尝试编写 ValueConatiner.class

public class ValueContainer implements Serializable {
    private static final long serialVersionUID = 2846820178517499793L;
    public String name;
    public MonetaryField buy;
    public MonetaryField sell;
    public MonetaryField revenue;
    public MonetaryField cost;
    public MonetaryField listing_fee;
    public MonetaryField sale_fee;
    public MonetaryField profit;
    public int quantity;
    public int investment;
    public int period;

    public ValueContainer(String n, MonetaryField b, MonetaryField s,
                          MonetaryField r, MonetaryField c, MonetaryField lf,
                          MonetaryField sf, MonetaryField p, int q,
                          int i, int per) {
            name = n;
            buy = b;
            sell = s;
            revenue = r;
            cost = c;
            listing_fee = lf;
            sale_fee = sf;
            profit = p;
            quantity = q;
            investment = i;
            try {
                    period = per;
            } catch(NumberFormatException e) {
                    System.out.println("No data. Enter a number.");
            }
    }
}

我试图在我持有 JMenuBar 的单独类中使用此方法将其写入磁盘。

private void saveFile() {
    if(!currentFile.exists()) {
        loadFile();
    }
    if(currentFile.exists()) {
        try {
            ValueContainer values = getValues();
            FileOutputStream f_out = new FileOutputStream(currentFile);
            ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
            try {
                obj_out.writeObject(values);
            } finally {
                obj_out.close();
                f_out.close();
            }
            System.out.println("Saved!");
        } catch(IOException e) {
            System.out.println(e);
        }
    }
}
4

3 回答 3

4

我只是要在黑暗中开枪然后说...

MonetaryField也需要可序列化。

于 2013-08-02T19:49:37.917 回答
1

...遍历图时,可能会遇到不支持 Serializable 接口的对象。在这种情况下,NotSerializableException 将被抛出,并将识别不可序列化对象的类。

那是来自javadocs。为了使您的 Instance 可序列化,对象图中的所有对象也必须是可序列化的。仔细检查是否是这种情况。

于 2013-08-02T19:54:20.147 回答
0

serializable如果类实现并且其所有非原始字段都是 ,则类是可序列化的serializable。大概MonetaryField不是serializable

于 2013-08-02T19:52:12.730 回答