[JAVA5.0] 자바 객체 직렬화하여 문자열 변수에 저장

자바 객체를 직렬화하여 직렬화한 문자열을 String 변수에 담아서 사용한다.

public class Test {
public static void main(final String[] args) {
try {
String s = new String();
List<Bean> beans = new ArrayList<Bean>();
for (int i = 0; i < 10; i++) {
Bean b = new Bean();
b.setVo(new VO());
beans.add(b);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(baos);
oout.writeObject(beans);
oout.close();
byte[] buf = baos.toByteArray();
s = new BASE64Encoder().encode(buf);
System.out.println(s);




byte[] rbuf = new BASE64Decoder().decodeBuffer(s);
if (rbuf != null) {
ObjectInputStream objectIn = new ObjectInputStream( new ByteArrayInputStream(rbuf));
Object obj = objectIn.readObject(); // Contains the object
List<Bean> rbeans = (List<Bean>) obj;
for (Bean bean : rbeans) {
System.out.println(bean.test);
System.out.println(bean.a.name());
System.out.println(bean.getVo().getA());

}
objectIn.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("asdfsadf");
}
}

위 소스는 간단하게 테스트를 해보기 위해 만들어진 소스이다.
상단 소스는 ArrayList의 객체를 직렬화하여 스트링 변수에 담는 과정이고

나머지는 스트링 변수에 담긴 내용을 다시 객체화시키는 과정이다.

이 방법은 정말 쓸모가 많은 소스이다.

특히 ActiveMQ 과 같은 것을 사용시 이 방법을 사용하면 보내는 곳과 받는곳에서 XML 이나 JSON 변환작업을 할 필요 없이 바로 객체를 직렬화하여 주고 받을 수 있다.

'언어 > Java' 카테고리의 다른 글

[Java5.0] Comparator 를 이용한 List 객체 정렬  (0) 2011.04.19
[JAVA5.0] 삼항연산자  (0) 2010.11.02
new  (0) 2010.10.27
Thread 간단 tip  (0) 2009.09.29
[JAVA5.0] 열거형 상수, enum 사용( Enumeration )  (0) 2009.03.24