자바에서는 객체를 파일에 저장하거나 네트워크로 전송하기 위해 데이터를 직렬화하고, 이를 다시 원래의 객체로 복원하기 위해 역직렬화를 사용합니다. 데이터 타입의 직렬화와 역직렬화는 자바에서 흔히 사용되며, 이를 통해 객체의 상태를 유지하고 전송할 수 있습니다.
직렬화(Serialization)
직렬화란 객체의 상태를 데이터 스트림으로 변환하는 과정입니다. 객체를 직렬화하면 데이터 스트림 형태로 저장할 수 있으며, 파일이나 네트워크에서 전송하거나 저장하는 데 사용할 수 있습니다.
자바에서는 Serializable
인터페이스를 구현하여 객체를 직렬화할 수 있습니다. Serializable
인터페이스를 구현한 클래스의 객체는 ObjectOutputStream
을 사용하여 직렬화할 수 있습니다.
import java.io.*;
public class SerializationExample {
public static void main(String[] args) {
// 직렬화할 객체 생성
Student student = new Student("John", 20, "1234567890");
try {
// 객체를 직렬화하여 파일에 저장
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(student);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in student.ser");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable {
private String name;
private int age;
private String studentId;
public Student(String name, int age, String studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
}
}
위의 예제에서는 Student
클래스가 Serializable
인터페이스를 구현하여 직렬화됩니다. ObjectOutputStream
을 사용하여 student.ser
파일에 객체를 직렬화하고 저장합니다.
역직렬화(Deserialization)
역직렬화란 직렬화된 데이터를 객체로 복원하는 과정입니다. 직렬화된 데이터를 읽어와 객체의 원래 상태를 복원할 수 있습니다.
자바에서는 ObjectInputStream
을 사용하여 역직렬화를 수행할 수 있습니다. 직렬화된 데이터를 읽어와 역직렬화를 수행한 후, 원래의 객체를 얻을 수 있습니다.
import java.io.*;
public class DeserializationExample {
public static void main(String[] args) {
Student student = null;
try {
// 직렬화된 데이터를 파일에서 읽어와 역직렬화
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
student = (Student) in.readObject();
in.close();
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Student class not found");
c.printStackTrace();
return;
}
// 역직렬화된 객체 사용
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("Student ID: " + student.getStudentId());
}
}
위의 예제에서는 student.ser
파일에서 직렬화된 데이터를 읽어와 역직렬화하여 Student
객체를 얻고, 객체의 상태를 출력합니다.
주의사항
- 직렬화된 객체를 역직렬화할 때, 클래스의 구조가 변경되었거나
Serializable
인터페이스가 구현되지 않은 경우InvalidClassException
이 발생할 수 있습니다. 이를 방지하기 위해 객체를 역직렬화할 때 클래스의 serialVersionUID를 설정하는 것이 좋습니다. - 객체를 직렬화할 때, 민감한 정보(비밀번호, 암호 등)가 포함되지 않도록 주의해야 합니다. 직렬화된 데이터는 외부로 노출될 수도 있기 때문에 보안을 고려하여야 합니다.
결론
자바에서 데이터 타입의 직렬화와 역직렬화는 객체를 파일에 저장하거나 네트워크로 전송하기 위한 중요한 기술입니다. 이를 통해 객체의 상태를 유지하고 전송할 수 있습니다. 직렬화와 역직렬화를 올바르게 사용하는 방법을 알면, 자바 애플리케이션에서 데이터를 효율적으로 관리할 수 있습니다.