보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

자바에서 transient 필드는 뭐하는 것일까?


객체내에 변수를 사용할때 transient로 지정하게 되면 직렬화(serializing), 또는 역직렬화(deserializing)시에 해당 변수는 직렬화 하지 않는 다는 것을 가리키는 것이다. 한마디로 하면 Object를 파일로 직접 저장할 때 직렬화 기능을 이용하는데, transient로 지정되지 않은 변수 값만 저장한다는 것이다.


간단히 테스트 코드를 작성 후 실행하면 다음 결과가 나온다.


package com.billyvme.serialize.sample;


import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;


public class TransientSample {


  public static final String FILENAME = "data.ser";


  /**

   * @param args

   * @throws IOException

   * @throws ClassNotFoundException

   */

  public static void main(String[] args) throws IOException,

      ClassNotFoundException {

    Point before = new Point();

    before.x = 7;

    before.y = 20;

    before.rho = (float) 3.14;

    before.theta = (float) 12.15;


    writeObject(before);


    Object after = readObject();

    System.out.print("Before : ");

    System.out.println(before);

    System.out.print("After  : ");

    System.out.println(after);

  }


  private static void writeObject(Object obj) throws IOException {

    FileOutputStream fos = new FileOutputStream(FILENAME);

    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(obj);

    oos.close();

    fos.close();

  }


  private static Object readObject() throws IOException, ClassNotFoundException {

    FileInputStream fis = new FileInputStream(FILENAME);

    ObjectInputStream ois = new ObjectInputStream(fis);

    Object result = ois.readObject();

    ois.close();

    fis.close();


    return result;

  }

}


class Point implements Serializable {

  int x, y;

  transient float rho, theta;


  @Override

  public String toString() {

    return String.format("x=%d, y=%d, rho=%f, theta=%f", x, y, rho, theta);

  }

}


위 코드를 실행해 보면 다음과 같은 결과가 출력 된다.


Before : x=7, y=20, rho=3.140000, theta=12.150000

After  : x=7, y=20, rho=0.000000, theta=0.000000


결과에서 보듯이 transient로 지정되지 않은 x,y 값만 다시 출력되는 것을 확인 할 수 있다. 

클래스 내에 암호 값이나 키 값을 속성 내에서 사용하는데 전송되거나 저장되면 안되는 값을 transient로 지정하면 좋을 것 같다. 

그런데 실제로 이 지시어를 써서 프로그래밍을 한 적이 없다. 매번 어플리케이션만 개발해서 그런걸까??

'개발자 > Java' 카테고리의 다른 글

자바 테스트를 위한 질문 정리  (0) 2013.09.24
Clone 메소드를 이용한 List의 객체 복사  (0) 2013.06.17
Posted by 빌리 :