Java & Kotlin

[Java 기능] 직렬화

Sue 2022. 2. 17. 16:13

직렬화 (serialization)

  • 객체가 인스턴스화 되면 메서드가 호출되면서 값이 계속 변할 수 있음
  • 인스턴스의 상태를 그대로 파일에 저장하거나 네트워크로 전송하고 이를 다시 복원하는 방식
  • 자바에서는 보조 스트림을 활용하여 직렬화를 제공 (ObjectInputStream, ObjectOutputStream)

 

Serializable 인터페이스

  • 직렬화는 인스턴스의 내용이 외부로 유출되는 것이므로 프로그래머가 해당 객체에 대한 직렬화 의도를 명시해야함
  • 직렬화 하려는 클래스가 Serializable 인터페이스를 구현하도록 하여 직렬화 명시
  • 구현 코드가 없는 marker interface
  • transient : 직렬화하지 않으려는 멤버 변수에 사용하는 키워드 (Socket 등 직렬화 할 수 없는 객체)

 

SerializationTest.java
  • readObject()시 클래스 정보 필요한데 클래스가 없을 수 있으므로 ClassNotFound Exception 걸어주어야 함
  • Serializable 인터페이스를 implements 하지 않으면 실행되지 않음
package ch17;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Person {	// implements Serializable
	
	String name;
	String job;
	
	public Person() {}
	
	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("serial.txt");
				ObjectOutputStream oos = new ObjectOutputStream(fos)) {
			
			oos.writeObject(personLee);	// 객체를 파일에 입력
			oos.writeObject(personKim);
		} catch(IOException e) {
			e.printStackTrace();
		}
		
		try(FileInputStream fis = new FileInputStream("serial.txt");
				ObjectInputStream ois = new ObjectInputStream(fis)) {
			
			Person pLee = (Person)ois.readObject();	// ClassNotFound 예외 처리 걸어줘야 함
			Person pKim = (Person)ois.readObject();
			
			System.out.println(pLee);
			System.out.println(pKim);
			
			} catch(IOException e) {
				e.printStackTrace();
			} catch(ClassNotFoundException e) {
				e.printStackTrace();
			}
	
	}
}

 

 

 


Externalizable 인터페이스

  • Serializable 인터페이스를 구현한 클래스는 writeObject() 또는 readObject() 메서드로 transient로 선언된 멤버변수 외에는 모두 직렬화
  • Externalizable 인터페이스를 구현한 클래스는 프로그래머가 직접 객체를 읽고 쓰는 코드를 구현
  • writeExternal(), readExternal() 메서드를 직접 구현해야함

 

Externalizable을 구현하는 Person 클래스
  • 직렬화 수행하지 않을 변수는 write와 read 메서드를 수행하지 않으면 됨
class Person implements Externalizable{
	
	...
    
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeUTF(name);	// String 값 직렬화
		out.writeUTF(job);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		name = in.readUTF();
		job = in.readUTF();
	}
}

 

 

※ 대부분은 Serializable 인터페이스를 많이 사용