Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 junit.framework.TestCase;
public class SerializationTest extends TestCase
{
public void test() throws Exception
{
deserialize(serialize(new Foo("serializable data")));
}
public byte[] serialize(Object instance) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(instance);
os.flush();
return baos.toByteArray();
}
public Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream is = new ObjectInputStream(bais);
return is.readObject();
}
public static class Foo implements Serializable
{
private final Object object;
public Foo(Object object)
{
this.object = object;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment