nicomp
nicomp

Reputation: 4647

Why does this serialization logic fail with 'unmatched serializable field(s) declared'?

A reproducible example:

package test;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;


public class mySerializable implements Serializable {

    private static int f;
    private static int g;

    private static final ObjectStreamField[] serialPersistentFields = {
            new ObjectStreamField("f", Integer.class),
            new ObjectStreamField("g", Integer.class),
    };

    public static void main(String[] args) {

        save();

    }
    public static void save() {
        try {
             FileOutputStream fileOut = new FileOutputStream("config" + ".ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
             out.writeObject(new mySerializable());
             out.close();
             fileOut.close();
        } catch (Exception ex) {
            System.out.println("save()" + ex.getLocalizedMessage());        }
    }
    public static int getF() {
        return f;
    }
    public static void setF(int f) {
        mySerializable.f = f;
    }
    public static int getG() {
        return g;
    }
    public static void setG(int g) {
        mySerializable.g = g;
    }
}

The program prints: save(): test.mySerializable; unmatched serializable field(s) declared

Upvotes: 0

Views: 200

Answers (1)

Andy Turner
Andy Turner

Reputation: 140326

You've got two problems:

  • f and g are static; static fields aren't serialized.
  • They're also of type int, not Integer.

Make them non-static, and refer to them using int.class.

Ideone demo

Upvotes: 1

Related Questions