package com.uet.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.uet.common.exception.SerializeException;
public class ObjectsSerializeUtil{
public static byte[] serialize(T value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] result = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
result = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return result;
}
@SuppressWarnings("unchecked")
public static T deserialize(Class resultClass,byte[] in) {
T result = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
result = (T) is.readObject();
is.close();
bis.close();
}
} catch (IOException e) {
throw new SerializeException(String.format("Caught IOException decoding %d bytes of data", in == null ? 0 : in.length) + e);
} catch (ClassNotFoundException e) {
throw new SerializeException(String.format("Caught CNFE decoding %d bytes of data", in == null ? 0 : in.length) + e);
} finally {
close(is);
close(bis);
}
return result;
}
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
throw new SerializeException(e);
}
}
}
}