Serialization Validation initial commit

Changes for Adding Tests Serialization Validation
1: Added utility Method.
2: Added Tests
This commit is contained in:
Amitabh Tiwari
2021-10-15 08:36:43 +05:30
parent 9e83c4503b
commit 723160c5cc
3 changed files with 114 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
package com.baeldung.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializationUtils {
public static <T extends Serializable> byte[] serialize(T obj)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
return baos.toByteArray();
}
public static <T extends Serializable> T deserialize(byte[] b, Class<T> cl)
throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
return cl.cast(o);
}
}