티스토리 뷰

 

 

[Serialization 객체 직렬화하기]



1. 객체를 직렬화 하면 객체의 상태를 저장할 수 있다.


2. 객체를 직렬화 하려면 ObjectOutputStream (java.io package)이 필요하다.


3. 스트림에는 연결 스트림과 연쇄 스트림이 있다.


4. 연결 스트림은 출발지나 목적지(보통 파일, 네트워크, 소켓, 연결, 콘솔 등)에 대한 연결을 나타낸다.


5. 연쇄 스트림은 출발지 또는 목적지에 연결할 수 없기 때문에 반드시 연쇄 스트림 또는 다른 스트림에 연쇄되어야 한다.


6. 객체를 직렬화 해서 파일로 저장하고 싶다면 FileOutput Stream을 만들고 그 스트림에 ObjectOutput Stream을 연쇄시킨다.


7. 객체를 직렬화 할 때에는 ObjectOutputStream의 writeObject(theObject) 메소드를 호출한다. FileOutputStream에 있는 메소드는 호출할 필요가 없다.


8. Serializable 인터페이스를 구현한 객체만 직렬화 할 수 있다. 어떤 클래스의 상위 클래스 중에 Serializable을 구현하는 클래스가 있다면 선언할 때 implements Serializable이라고 쓰지 않아도 자동으로 직렬화 할 수 있는 클래스가 된다.


9. 객체가 직렬화 되면 그 객체와 연관된 모든 객체가 직렬화 된다. 즉, 직렬화된 객체의 인스턴스 변수에 의해 참조된 객체들도 모두 직렬화 되고, 그 객체들에서 참조하는 객체들도 모두 직렬화 되고... 이런 식으로 모든 연관된 것들이 직렬화 된다.


10. 연관된 객체 중에 직렬화 할 수 없는 것이 하나라도 있으면 직렬화 과정에서 그 인스턴스 변수를 건너뛰지 않는 이상 실행중에 예외가 던져진다.


11. 직렬화할 때 어떤 객체를 건너뛰고 싶다면 transient 키워드를 사용한다. 그 변수는 나중에 복구될 때 null(reference type) 또는 기본 값(primitive type)이 할당 된다.


12. 역직렬화를 할 때에는 그 JVM에 해당 객체를 저장한 것과 같은 순서로 읽어오게 된다.


13. readObject()의 리턴 유형은 Object이므로 역직렬화 과정에서 원래 유형으로 casting해야 한다.


14. 정적 변수는 직렬화 되지 않는다. 정적 변수값은 한 유형에 속하는 모든 객체들이 클래스에 들어있는 단 한 개 뿐인 값을 공유하기 때문에 특정 객체 상태의 일부로 저장할 이유가 전혀 없다.


[예제]

import java.io.*;


public class GameSaverTest

{

    GameCharacter one = new GameCharacter(50, "Elf", new String[] {"bow", "sword", "dust"});

    GameCharacter two = new GameCharacter(200, "Troll", new String[] {"bare hands", "big ax"});

    GameCharacter three = new GameCharacter(120, "Magician", new String[] {"spells", "invisibility"});


    try{

          ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser"));

          os.writeObject(one);

          os.writeObject(two);

          os.writeObject(three);

          os.close();

    } catch(IOException ex) {

          ex.printStackTrace();

    }

    one = null;

    two = null;

    three = null;


    try{

          ObjectInputStream is = new ObjectInputStream(new FileInputStream("Game.ser"));

          GameCharacter oneRestore = (GameCharacter) is.readObject();

          GameCharacter twoRestore = (GameCharacter) is.readObject();

          GameCharacter threeRestore = (GameCharacter) is.readObject();


          System.out.println("One's type : " + oneRestore.getType());

          System.out.println("Two's type : " + twoRestore.getType());

          System.out.println("Three's type : " + threeRestore.getType());

    } catch(Exceptio ex){

          ex.printStackTrace();

    }

}



위에서 사용된 GameCharacter class


import java.io.*;


public class GameCharacter implements Serializable

{

    int power;

    String type;

    String[] weapons;


    public GameCharacter(int p, String t, String[] w)

    {

       power = p;

       type = t;

       weapons = w;

    }


    public int getPower()

    {

       return power;

    }


    public String getType()

    {

       return type;

    }


    public String getWeapons()

    {

       String weaponList = "";


       for(int i=0; i<weapons.length; i++)

       {

          weaponList += weapons[i] + " ";

       }

        return weaponList;

    }

}



참고

http://shoutrock.egloos.com/4187938

 

'[IT] > 컴퓨터' 카테고리의 다른 글

[IT][Elcipse 스텝 단위 디버깅]  (0) 2013.03.31
[IT][Maven의 POM 파일 구조]  (0) 2013.03.31
[IT][JUnit이란?]  (0) 2013.03.31
[IT][JUnit의 TestSuite 기본알기]  (0) 2013.03.31
[IT][JUnit의 TestCase 기본알기]  (0) 2013.03.31
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함