개요

자바에서 Object를 serialize할일이 생겼다. 그래서 찾아보다가 앞으로도 유용히 쓸 것 같아서 SerializeUtil 클래스를 하나 만들어 둔다.

방법은 어떤 Java Object든 Serializable을 상속 받은 VO 객체가 있다면 이를 아래의 유틸로 변환하면 된다. 유의 사항은 VO의 하위 VO(예: 멤버 VO)도 모두 Serialzable을 implement해야 한다.

클래스명이 영어 어법상 맞지 않지만 한국인 눈에는 직관적일 수 있으니 패스~

코드

아래 클래스는 Object를 byte[] 혹은 String으로 Serilize하거나 Serialze된 결과를 반대로 Object로 Deserialize하는 역할을 한다.

public class SerializeUtil {

    /**
     * Read the object from Base64 string.
     */
    public static Object fromString(String s) throws IOException,
        ClassNotFoundException {
    byte[] data = Base64.getDecoder().decode(s);
    ObjectInputStream ois = new ObjectInputStream(
        new ByteArrayInputStream(data));
    Object o = ois.readObject();
    ois.close();
    return o;
    }

    /**
     * Write the object to a Base64 string.
     */
    public static String toString(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);
    oos.close();
    return Base64.getEncoder().encodeToString(baos.toByteArray());
    }

    /**
     * Read the object from Base64 string.
     */
    public static Object fromByteArray(byte[] bytes) throws IOException,
        ClassNotFoundException {
    byte[] data = bytes;
    ObjectInputStream ois = new ObjectInputStream(
        new ByteArrayInputStream(data));
    Object o = ois.readObject();
    ois.close();
    return o;
    }

    /**
     * Write the object to a byte[].
     */
    public static byte[] toBytes(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);
    oos.close();
    return baos.toByteArray();
    }
}