Skip to content

Instantly share code, notes, and snippets.

@twolfe18
Last active August 29, 2015 14:17
Show Gist options
  • Save twolfe18/24d3ffcb332a9021460d to your computer and use it in GitHub Desktop.
Save twolfe18/24d3ffcb332a9021460d to your computer and use it in GitHub Desktop.
One more reason I hate Java serialization...
package sanbox;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializationBugMWE {
public static interface Fooable extends Serializable {
public void foo();
}
public static class FooProvider {
protected int f;
public void foo() {
System.out.println("foo here!");
}
}
public static class Derived extends FooProvider implements Fooable {
public Derived(int f) {
this.f = f;
}
public int getF() {
return f;
}
}
public static void main(String[] args) throws Exception {
Derived d = new Derived(5);
File f = new File("/tmp/a");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
oos.writeObject(d);
}
Derived d2 = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
d2 = (Derived) ois.readObject();
}
System.out.println(d.getF() + " vs " + d2.getF());
// prints "5 vs 0"
}
}
@twolfe18
Copy link
Author

Woah, I don't remember java serialization leaving hooks for custom serializers! Either A) I am misunderstanding how the two methods below work or B) someone on StackOverflow lied to me about java not allowing custom serialization.

 private void writeObject(java.io.ObjectOutputStream out) throws IOException
 private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment