객체 직렬화(serialization)

Updated:

객체 직렬화(Serialization)

  • 객체를 저장하거나 네트워크로 전송하기 위해 연속적인 데이터로 변환하는 것
  • 반대의 경우는 역 직렬화(deserialization)
  • 직렬화 되기 위한 조건
    • Serializable 인터페이스를 구현할 것.
    • 클래스의 모든 멤버가 Serializable 인터페이스를 구현해야 함.
    • 직렬화에서 제외하려는 멤버는 transient 선언
class Person implements Serializable{ //직렬화 필수조건
	private String name;
	private int age;

	private transient String ssn; //직렬화 제외
	private LogInfo lInfo; //직렬화 필요
}
  • serialVersionUID
    • 클래스의 변경 여부를 파악하기 위한 유일한 키
    • 직렬화 할 때의 UID와 역직렬화 할때의 UID가 다를 경우 예외 발생
    • 멤버 변경으로 인한 컴파일 시마다 변경 -> InvalidClassException 초래
    • 직렬화되는 객체에 대해서 serialVersionUID 설정 권장.

객체직렬화 예시

  • 직렬화 대상 클래스
public class Person implements Serializable {

	private static final long serialVersionUID = 1L;
	private String id;
	private transient String pass; // 민감한 데이터
	private Address addr; // has a 관계의 다른 객체
	private String nick;

	public Person(String id, String pass, String zipCode, String city) {
		this.id = id;
		this.pass = pass;
		this.addr = new Address(zipCode, city);
	}

	@Override
	public String toString() {
		return "[id=" + id + ", pass=" + pass + ", addr=" + addr + "]";
	}

	class Address implements Serializable {
		private String zipCode;
		private String city;

		public Address(String zipCode, String city) {
			this.zipCode = zipCode;
			this.city = city;
		}

		public String toString() {
			return "Address [zipCode=" + zipCode + ", city=" + city + "]";
		}
	}
}

ObjectInputStream, ObjectOutPutStream

  1. ObjectInputStream()
    • public ObjectOutputSStream(OutputStream out) thrwos IOException
    • out을 이용해 ObjectOutputStream 객체를 생성한다.
  2. writeObject()
    • public final void write Object(Object obj)throws IOException
    • obj를 직렬화해서 출력한다.
  3. ObjectInputStream()
    • public ObjectInputStream(InputStream in) throws IOException
    • in을 이용해 ObjectInputStream 객체를 생성한다.
  4. readObject()
    • public final Object readObject() throws IOException, classNotFoundException
    • 직렬화된 데이터를 역질렬화해서 Object로 리턴한다.

보조스트림활용한 직렬화 예시

public class ObjectStreamTest {
	public static void main(String[] args) {
		// write();
		read();
	}

	private static File target = new File("c:/Temp/objPerson.dat");

	private static void write() {
		Person person = new Person("홍길동2", "pass1234", "123-456", "seoul");
		// TODO: person을 target에 저장하시오.
		try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(target));) {
			// 객체 저장
			output.writeObject(person);
			System.out.println("저장 완료!!");
		} catch (IOException e) {
			e.printStackTrace();

		}
		// END:
	}

	private static void read() {
		// TODO: target에서 person을 읽어서 내용을 출력하시오.
		try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(target))) {
			// 객체 로딩
			Object readObj = input.readObject();
			if (readObj != null && readObj instanceof Person) {
				Person p = (Person) readObj;
				System.out.println("로딩 완료!! " + p);
			}
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		// END:
	}
}

Leave a comment