Java/Java 올인원 패키지
34. 직렬화 (Java)
GrapeMilk
2020. 4. 6. 22:17
Goal
- 직렬화에 대해 알아본다
- 직렬화 가능 여부를 명시하는 Serializable 인터페이스에 대해 알아본다
- 코드 예시를 통해 실습한다.
1. 직렬화 (Serialization)
- 인스턴스의 상태를 그대로 저장하거나 네트윅으로 전송하고 이를 다시 복원 (Deserialization) 하는 방식
- ObjectInputStream과 ObjectOutputStream이라는 보조스트림을 사용
- 프레임워크에서 내부적으로 많이 쓰임
2. Serializable 인터페이스
- 직렬화는 인스턴스의 내용이 외부(파일, 네트워크)로 유출되는 것이므로 프로그래머가 객체의 직렬화 가능 여부를 명시함
- 구현 코드가 없는 mark interafce인 Serializable 인터페이스를 통해 직렬화 가능 여부를 명시 (명시하지 않으면 직렬화 불가)
- Externalizble 인터페이스는 구현할 수 있는 메서드가 존재함.
3. 코드 예시
package serialization;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable { //Externalizable (구현할 수 있는 메서드가 있음)
String name;
transient String job; //transient : 해당 변수는 직렬화 하지 않는다. (ex 소켓 등에 사용)
public Person(String name, String job) {
this.name = name;
this.job = job;
}
public String toString() {
return name + "," + job;
}
}
public class SerializationTest {
public static void main(String[] args) {
Person personLee = new Person("이순신", "엔지니어");
Person personKim = new Person("김유신", "선생님");
try (FileOutputStream fos = new FileOutputStream("setial.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos)){
oos.writeObject(personLee);
oos.writeObject(personKim);
} catch (IOException e) {
System.out.println(e);
}
try (FileInputStream fis = new FileInputStream("setial.dat");
ObjectInputStream ois = new ObjectInputStream(fis)){
Person p1 = (Person)ois.readObject();
Person p2 = (Person)ois.readObject();
System.out.println(p1);
System.out.println(p2);
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
}
}
4. 실행결과
- 직렬화를 통해 작성한 인스턴스의 내용이 setial.dat파일에 적혀있는 것을 알 수 있다.
- 인스턴스의 내용은 바이너리 데이터이기 때문에 알아볼 수는 없다.
- 해당 코드를 읽어보면 인스턴스의 내용이 출력되는 것을 알 수 있다.
- String job 변수는 transient처리를 했기 때문에 직렬화하지 않아 null값이 출력된다.
- *transient : 해당 변수를 직렬화 하지 않음.