클래스의 인스턴스를 직렬화하는 방법은 무엇인가요?
import java.io.*;
public class MyClass implements Serializable {
// 클래스 내용
}
public class Main {
public static void main(String[] args) {
// 객체 생성
MyClass obj = new MyClass();
// 객체를 파일로 직렬화
try {
FileOutputStream fileOut = new FileOutputStream("serialized.obj");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.println("객체가 직렬화되었습니다.");
} catch (IOException e) {
e.printStackTrace();
}
// 파일에서 객체를 역직렬화
try {
FileInputStream fileIn = new FileInputStream("serialized.obj");
ObjectInputStream in = new ObjectInputStream(fileIn);
MyClass newObj = (MyClass) in.readObject();
in.close();
fileIn.close();
System.out.println("객체가 역직렬화되었습니다.");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
위의 예시에서는 MyClass라는 클래스를 Serializable 인터페이스를 구현하여 직렬화 가능하게 만들었습니다. 객체를 직렬화하려면 ObjectOutputStream을 사용하여 객체를 파일로 쓰고, ObjectInputStream을 사용하여 파일에서 객체를 읽어와 역직렬화합니다. 이를 통해 클래스의 인스턴스를 직렬화하고 역직렬화할 수 있습니다.
#직렬화 #Java