Created
February 1, 2015 20:05
-
-
Save ansig/bd73e05f67643a6dd074 to your computer and use it in GitHub Desktop.
Serialize and deserialize an object. Also demonstrates how constructors are invoked on deserialization.
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
import java.io.*; | |
/** | |
* Serialize and deserialize an object. Also demonstrates how constructors are invoked on deserialization. | |
*/ | |
public class SerializeDeserialize { | |
public static void main(String[] args) throws IOException, ClassNotFoundException { | |
Bar myBar = new Bar(); | |
System.out.printf("After initialization:%n"); | |
System.out.printf("%s%n", myBar); | |
myBar.a = 3; | |
myBar.b = 4; | |
System.out.printf("Before serialization:%n"); | |
System.out.printf("%s%n", myBar); | |
System.out.printf("Serializing...%n"); | |
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myBar.obj")); | |
oos.writeObject(myBar); | |
System.out.printf("Deserializing...%n"); | |
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myBar.obj")); | |
Bar deserializedBar = (Bar) ois.readObject(); | |
System.out.printf("After deserialization:%n"); | |
System.out.printf("%s%n", deserializedBar); | |
} | |
} | |
class Foo { | |
int a = 1; | |
Foo() { | |
System.out.printf("Foo constructor%n"); | |
} | |
} | |
class Bar extends Foo implements Serializable { | |
static final long serialVersionUID = 1l; | |
int b = 2; | |
Bar() { | |
System.out.printf("Bar constructor%n"); | |
} | |
public String toString() { | |
return String.format("a=%d%nb=%d%n", a, b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment