سؤال

I have a class implementing Serializable, but I'm having trouble finding why it throws this exception whenever I try to write it it disk. I'm trying to write 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.");
            }
    }
}

I am attempint to write it to disk using this method in a separate class where I hold my 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);
        }
    }
}
هل كانت مفيدة؟

المحلول

I'm just going to take a shot in the dark and say...

MonetaryField needs to be Serializable as well.

نصائح أخرى

...When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Thats from the javadocs. For your Instance to be serializable all objects in the object graph must also be serializable. Double check that this is the case.

Class is serializable if it implements serializable AND all its non-primitive fields are serializable. Probably MonetaryField is not serializable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top