java.io.Serializable 인터페이스 상속받는 객체
import java.io.Serializable;
// 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 "Member{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
// 직렬화 실행
public static void main(String[] args) throws IOException {
Member member = new Member("Lee Dohun", "dohun@abc.com", 28);
byte[] serializedMember;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(member); // oos 에 직렬화의 대상인 member 객체를 전달
serializedMember = baos.toByteArray();
// toByteArray() 메서드를 통해 직렬화 수행 ( Object -> Byte )
}
}
System.out.println(Base64.getEncoder().encodeToString(serializedMember));
// 직렬화된 Member 값을 base64 method로 인코딩
// 인코딩된 Member 값 : rO0ABXNyABpjb20uZXhhbXB...8
}
}
public static void main(String[] args){
// 직렬화 예제에서 생성된 base64 데이터
String base64Member = "rO0ABXNyABpjb20uZXhhbXB...8";
byte[] serializedMember = Base64.getDecoder().decode(base64Member);
try (ByteArrayInputStream bais = new ByteArrayInputStream(serializedMember)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
// 역직렬화된 Member 객체를 읽어온다.
Object objectMember = ois.readObject();
Member member = (Member) objectMember;
System.out.println(member);
}
감사합니다~