Skip to content

Instantly share code, notes, and snippets.

@MarkZhangTW
Created April 13, 2020 06:25
Show Gist options
  • Save MarkZhangTW/7ad5b011c2cef05db8b9e007b4e94279 to your computer and use it in GitHub Desktop.
Save MarkZhangTW/7ad5b011c2cef05db8b9e007b4e94279 to your computer and use it in GitHub Desktop.
Demo of Java Serialization
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
class JavaSerializationDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Sub originSub = new Sub(456, "aaa");
System.out.println(originSub);
String serialized = serialize(originSub);
Sub newSub = desiralize(serialized);
System.out.println(newSub);
System.out.println(newSub.getString());
System.out.println(newSub.getNumber());
}
// ObjectOutputStream will not serialized the class that has not implemented Serializable
static class Base implements Serializable {
private final int number;
public Base(final int number) {
this.number = number;
// Shows that constructor will not be called when deserialized
System.out.println("Base's constructor was called.");
}
protected final int getNumber() {
return this.number;
}
}
static class Sub extends Base {
private final String string;
public Sub(final String string) {
this(123, string);
// Shows that constructor will not be called when deserialized
System.out.println("Sub's constructor with one parameter was called.");
}
public Sub(final int number, final String string) {
super(number);
this.string = string;
// Shows that constructor will not be called when deserialized
System.out.println("Sub's constructor with two parameters was called.");
}
public String getString() {
return this.string;
}
}
static String serialize(Serializable serializable) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(serializable);
}
// Data will probably not match format of String
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
static <T> T desiralize(String serialized) throws IOException, ClassNotFoundException {
byte[] data = Base64.getDecoder().decode(serialized);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bais);
T deserialized = (T) ois.readObject();
return deserialized;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment