Last active
August 29, 2015 14:17
-
-
Save twolfe18/24d3ffcb332a9021460d to your computer and use it in GitHub Desktop.
One more reason I hate Java serialization...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} |
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
@twolfe18: I haven't gone through the Java API. Are all output "openable" resources guaranteed to be closed, prior to reading in the object?