자바 직렬화 시 transient 키워드가 붙은 변수는 null이 된다

Seungyeon Choi·2022년 8월 7일
0

자바

목록 보기
5/5

업무 중 자바 코드에서 transient키워드를 보았다.
낯선 키워드여서 검색을 해보았더니 객체 직렬화 관련된 내용이었다!!

예시

부리또 클래스가 있다.

이 부리또 클래스를 직렬화시켜서 전달하려하는데,
요리한 사람의 정보는 제외시키려고 한다.

public class Burrito implements Serializable {
    private String name;
    private int price;
    private transient String cook; //요리한 사람
}

어떻게 할 수 있을까!?!

그럴 때 java에서는 transient 키워드를 제공한다.

객체의 모든 변수를 직렬화시키지 않기 위해서 별도의 처리 없이, 위 키워드만 붙여주면 해당 변수는 null로 셋팅된다.

테스트코드로 동작 확인해보기

    @Test
    public void transient키워드가있는_변수는_직렬화시_null이_된다() throws IOException, ClassNotFoundException {
        // given
        Burrito burrito = new Burrito("파인애플 부리또", 5000, "부리뚠");

        // when
        byte[] serializedBurrito = serialize(burrito);

        //then
        Burrito deSerializeBurrito = deSerialize(serializedBurrito);
        assertThat(burrito.getCook()).isEqualTo("부리뚠");
        assertThat(deSerializeBurrito.getCook()).isNull(); //transient가 있는 cook변수는 직렬화 시 null이 됨
    }

    private byte[] serialize(Burrito burrito) throws IOException {
        byte[] serializedBurrito;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(burrito);
            serializedBurrito = byteArrayOutputStream.toByteArray();
        }
        return serializedBurrito;
    }

    private Burrito deSerialize(byte[] serializedBurrito) throws IOException, ClassNotFoundException {
        Burrito burrito;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedBurrito);
             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            // 역직렬화된 Member 객체를 읽어온다.
            Object objectBurrito = objectInputStream.readObject();
            burrito = (Burrito) objectBurrito;
        }
        return burrito;
    }

profile
캘린더 만드는 개발자입니당

0개의 댓글