Java에서 Serializable 이라는 Interface가 있다.

이 Interface는 객체 직렬화인데, 이는 어떤 구조화된 객체를

Bytes Stream으로 전송하는 것을 말한다.

Serializable Interface를 구현한 Class는 직렬화가 가능하여

writeObject(Object obj) 나 readObject(Object obj) 등을 통해

전송이 가능하다.

Serializable의 예를 보도록 하자

import java.io.*;

class NonSerial
{
int v1;
public NonSerial() // needed for serialzation
{}

public NonSerial( int v1 ) {
this.v1 = v1;
}
}

public class MyList extends NonSerial implements Serializable
{
int v2;
transient String v3;
MyList next;
public MyList(int v1, int v2, String v3) {
super(v1);
this.v2 = v2;
this.v3 = v3;
}

public void print() {
System.out.print(v1 + ", " + v2 + ", " + v3 + ": ");
if (next == null)
System.out.println();
else
next.print();
}

public static void main(String[] args) {
MyList node1 = new MyList(1, 11, "first");
MyList node2 = new MyList(2, 12, "second");
MyList node3 = new MyList(3, 13, "third");
node1.next = node2;
node2.next = node3;
node3.next = null;
try {

FileOutputStream outFile
= new FileOutputStream("test.out");
ObjectOutput out = new ObjectOutputStream(outFile);
out.writeObject(node1);
out.close();

FileInputStream inFile
= new FileInputStream("test.out");
ObjectInput in = new ObjectInputStream(inFile);
MyList inNode = (MyList) in.readObject();

node1.print();
inNode.print();

in.close();
} catch( Exception e ) {
e.printStackTrace();
}
}
}


이 예제는 MyList Class가 Serializable Interface를 상속받지 않은 Class인

NonSerial 이라는 Class를 상속 받고 Serializable을 구현하였기에

NonSerial Class에 있는 v1 변수의 값은 기록되지 않고,

MyList에 있는 v2 변수와 next 변수만이 전송되어 기록되어지는 모습을 보인다.

MyList의 내부적인 모습은 다음과 같다.



이때 transient로 선언이 된 v3는 Serializable Interface를 구현한 MyList Class의

멤버 변수 임에도 불구하고 Serializable 특성을 가지지 않게 되어

실제 writeObject()나 readObject()함수를 사용하여도 전송되지 않는다.

따라서 위에 MyList를 실행한 결과는

1, 11, first: 2, 12, second: 3, 13, third:
0, 11, null: 0, 12, null: 0, 13, null:

이 된다.

또한 "test.out"의 파일을 열어보면 다음과 같은 기록이 보인다.

ы ?sr ?MyList?熬[?f? ?I ?v2L ?nextt ?LMyList;xp ?sq ~ ?sq ~
p

위에 MyList라는 문자가 듬성듬성 보인다.

이를 이용해 읽어들일때에는 다시 MyList를 생성하여 그 객체에 채워 넣은뒤 리턴하게 된다.



이때 주의 해야 할 점은 Serializable을 이용하여 전송을 할경우

위의 예처럼 Node1만을 writeObject()하여도 Node1,2,3가 모두

연달아 전송이 된다는 것이다. 이는 Node1에 있는 next 변수가 node2를 가리키고 있기때문에 따라가서 실제 객체를 저장하는 것이며

읽을때에도 또안 readObject()를 수행하면 자동으로 연결되어 있는 객체는 모두 read 된다.

유의 할 것!!!

+ Recent posts