Serialization

From APIDesign

Revision as of 16:59, 23 September 2013 by JaroslavTulach (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

Java has built in serialization mechanism based around Serialization which NetBeans used to use a lot at the end of last century. We moved away from it as it slowed down start (a lot of reflection) and was too automatic (many developers just could not understand what they are doing and keep BackwardCompatibility).

Can One Change Value of a final field?

Today, at JavaOne2013 I've noticed a question whether custom deserialization can modify final field. So here is the answer:

public final class App implements Serializable {
    private final int value;
 
    public App(int value) {
        this.value = value;
    }
 
    public int getValue() {
        return value;
    }
 
    private final void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        try {
            ObjectInputStream.GetField fields = ois.readFields();
            int newValue = fields.get("value", 0);
            Field f = App.class.getDeclaredField("value");
            f.setAccessible(true);
            f.setInt(this, newValue);
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }
}
 
public class AppTest {
    @Test public void deserialize() throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(new App(10));
        oos.close();
 
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(is);
        App app = (App) ois.readObject();
        ois.close();
 
        assertEquals(app.getValue(), 10);
    }
}
Personal tools
buy