<aside> 💡 기본 직렬화를 피하고 커스텀 직렬화를 사용하라

</aside>

커스텀 직렬화

직렬화 & 역직렬화할때 호출되는readObject() 와writeObject() 는 기본적으로 모든 요소에 대해 자동 직렬화 한다. 그런데 이 메서드들을 직렬화할 클래스에 별도로 재정의 해주면 직렬화를 선택적으로 조작할 수 있게 된다.

예시

고객 비밀번호를 함께 직렬화하지 않으려고 하는 경우

class Customer implements Serializable {
    int id; // 고객 아이디
    String name; // 고객 닉네임
    String password; // 고객 비밀번호
    int age; // 고객 나이

    public Customer(int id, String name, String password, int age) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
    }

    // 직렬화 동작 재정의 -> password가 직렬화되지 않음 
    private void writeObject(ObjectOutputStream out) throws IOException{
        out.writeInt(id);
        out.writeObject(name);
        out.writeInt(age);
    }

    // 역직렬화 동작 재정의
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
        this.id = in.readInt();
        this.name = (String) in.readObject();
        this.age = in.readInt();
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", password='" + password + '\\'' +
                ", name='" + name + '\\'' +
                ", age=" + age +
                '}';
    }
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
    Customer user = new Customer(1, "홍길동", "123123", 40);
    String fileName = "Customer.ser";

    // 직렬화
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
    out.writeObject(user);
    out.close();

    // 역직렬화
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)));
    Customer deserialized = (Customer) in.readObject();
    in.close();

    System.out.println(deserialized);
}

(기본)직렬화

일반적인 개발에서는 일정에 쫓기는 경우 API설계에 집중하고, 구현에는 크게 신경쓰지 않는 것(돌아만 가게 구현하고 추후 업그레이드)이 하나의 좋은 전력이다.