기본(primitive) 타입
과 java.io.Serializable
인터페이스를 상속받은 객체는 직렬화 할 수 있는 기본 조건을 갖는다.
import java.io.Serializable;
public class Member implements Serializable {
private String name;
private String email;
private int age;
public Member(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
@Override
public String toString() {
return String.format("Member{name='%s', email='%s', age='%s',", name, email, age);
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
public class ObjectSerializableExam {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Member member = new Member("임준영", "a790077714@gmail.com", 30);
byte[] serializedMember;
// 직렬화
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(member);
// 직렬화된 member 객체
serializedMember = baos.toByteArray();
// base64로 인코딩한 문자열
String base64Member = Base64.getEncoder().encodeToString(serializedMember);
// base64로 디코딩한 문자열
byte[] deserializedMember = Base64.getDecoder().decode(base64Member);
// 역직렬화
ByteArrayInputStream bais = new ByteArrayInputStream(deserializedMember);
ObjectInputStream ois = new ObjectInputStream(bais);
Object objectMember = ois.readObject();
Member readMember = (Member) objectMember;
System.out.println(member);
}
}
[결과]