'. '

Serialization

From APIDesign

(Difference between revisions)
Jump to: navigation, search
Current revision (16:59, 23 September 2013) (edit) (undo)
(Can One Change Value of a final field?)
 
Line 3: Line 3:
== Can One Change Value of a '''final''' field? ==
== 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:
+
Today, at [[JavaOne2013]] I've noticed a question whether custom deserialization can modify '''final''' field. So here is the answer:
<source lang="java">
<source lang="java">

Current revision

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