본문 바로가기
Old Posts/Linux

[Java] transient 키워드 의미

by A6K 2022. 2. 13.

자바의 transient 키워드를 알아보기 전에 '직렬화(Serialization)'와 '역직렬화(Deserialization)'에 대해서 이해하고 넘어가야 한다.

직렬화와 역직렬화

'직렬화(Serialization)'는 JVM 메모리에 있는 객체를 바이트 스트림으로 변환하는 작업을 말한다. 주로 메모리에 있는 객체를 파일로 쓰거나 네트워크를 통해 다른 JVM으로 전송하는 동작이 필요할 경우 사용한다. 이렇게 변환된 바이트 스트림을 다시 자바 객체로 변환하는 것을 '역직렬화(Deserialization)'라고 한다.

transient 키워드

자바의 transient 키워드는 객체의 필드 중에 직렬화하지 않을 것들을 지정하기 위해 사용한다. 즉, transient 키워드가 붙은 필드의 값은 직렬화 작업에서 제외된다.

public class User implements Serializable {
    private static final long serialVersionUID = -2936687026040123549L;

		private String name;
		private transient String socialSecurityID;
		private transient String address;
}

예를 들어 위에서 정의된 User 클래스를 직렬화할 때, transient 키워드가 붙은 socialSecurityID 필드와 address 필드는 직렬화되지 않는다.

반대로 역직렬화 될 때에는 transient 키워드가 붙은 필드의 경우 타입별 기본 값이 할당된다.

transient 키워드를 쓰는 경우

일반적으로 transient 키워드는 다음과 같은 경우 사용한다.

  • 민감한 정보를 직렬화하지 않도록 제외하고 싶은 경우
  • 필드의 값이나 객체가 계산해서 얻을 수 있는 값인 경우

첫 번째 경우는 위에서 설명했기 때문에 그냥 넘어가자.

두 번째 경우는 필드가 참조하는 다른 객체를 직렬화하지 않도록 막고 싶을 때 사용한다. 예를 들어 DB에 접속해서 값을 가져오는 객체를 멤버로 갖고 있다면, 이 객체 자체를 직렬화하는 것보다는 DB에 접속할 수 있는 주소나 ID, 패스워드 정보를 이용해서 역직렬화할 때 객체를 새로 생성하는게 옳을 수 있다. 응용해서 쓰자.

transient와 static, final

transient 키워드와 static 키워드를 함께 쓰는 경우가 있는데 이 경우 transient 키워드는 의미가 없다. static 필드 자체가 객체와 관련있는게 아니기 때문이다.

비슷하게 transient 키워드와 final 변수 역시 transient의 효과가 없다. final 변수는 객체의 값을 바로 초기화 시키기 때문이다.

transient 예제

import java.io.*;

public class Test implements Serializable {

	public int number1 = 10;
	public String name1 = "name1";

	public transient int number2 = 200;
	public transient String name2 = "name2";

	public static transient int number3 = 200;
	public final transient String name3 = "name3";

	public static void main(String[] args) throws Exception
	{
		Test input = new Test();

		// 직렬화
		FileOutputStream fos = new FileOutputStream("file");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(input);

		// 역직렬화
		FileInputStream fis = new FileInputStream("file");
		ObjectInputStream ois = new ObjectInputStream(fis);
		Test output = (Test)ois.readObject();
		System.out.println("name1 = " + output.name1);
		System.out.println("name2 = " + output.name2);
		System.out.println("name3 = " + output.name3);
		System.out.println("number1 = " + output.number1);
		System.out.println("number2 = " + output.number2);
		System.out.println("number3 = " + output.number3);
	}
}

출력값

name1 = name1
name2 = null
name3 = name3
number1 = 10
number2 = 0
number3 = 200

예제 코드를 실행해보면 transient 키워드가 붙은 name2와 number2는 각각 int와 String 타입의 기본 값이 할당된 것을 볼 수 있다.

또 static과 final이 붙은 경우에는 transient 키워드의 효과가 없는 것을 볼 수 있다.

댓글