'. '

Serialization

From APIDesign

(Difference between revisions)
Jump to: navigation, search
(New page: Java has built in serialization mechanism based around {{JDK|java/io|Serialization}} which NetBeans used to use a lot at the end of last century. We moved away from it as it slowed...)
Line 17: Line 17:
}
}
-
void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+
private final void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
try {
try {
ObjectInputStream.GetField fields = ois.readFields();
ObjectInputStream.GetField fields = ois.readFields();
Line 23: Line 23:
Field f = App.class.getDeclaredField("value");
Field f = App.class.getDeclaredField("value");
f.setAccessible(true);
f.setAccessible(true);
-
f.setInt(this, value);
+
f.setInt(this, newValue);
} catch (Exception ex) {
} catch (Exception ex) {
throw new IOException(ex);
throw new IOException(ex);
Line 29: Line 29:
}
}
}
}
-
 
public class AppTest {
public class AppTest {

Revision as of 16:54, 23 September 2013

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