자바에서 내부 클래스의 직렬화(Serialize)
Joonas' Note
자바에서 내부 클래스의 직렬화(Serialize) 본문
객체를 그대로 파일에 저장하기 위해 직렬화를 시도했고 코드는 아래와 같았다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class World { | |
public World() { } | |
public class Person implements Serializable { | |
private static final long serialVersionUID = 1L; | |
private String name; | |
public Person() { } | |
public String toString() { | |
return "{" + name + "}"; | |
} | |
} | |
private Person person = new Person(); | |
synchronized public void save() { | |
try { | |
FileOutputStream fos = new FileOutputStream("save.ser"); | |
BufferedOutputStream bos = new BufferedOutputStream(fos); | |
ObjectOutputStream oos = new ObjectOutputStream(bos); | |
oos.writeObject(person); | |
oos.close(); | |
} catch (Exception e) { | |
// TODO: handle exception | |
e.printStackTrace(); | |
} | |
} | |
} |
그런데 이상하게도 java.io.NotSerializableException 가 발생하면서 제대로 동작하지 않았다.
stackoverflow에서 그 답변을 찾을 수 있었는데, 내부 클래스를 직렬화하기 위해서는 외부 클래스를 인스턴스화 해야하기 때문에 그렇다고 한다.
참고한 링크: https://stackoverflow.com/questions/7144912/why-is-a-serializable-inner-class-not-serializable
'개발 > Java' 카테고리의 다른 글
Java의 instanceof 결과 정리 (0) | 2024.07.31 |
---|---|
[JUnit5] Lifecycle 호출 순서 (0) | 2022.07.27 |
[Java/JavaDoc] @see, @inheritDoc (0) | 2022.04.15 |
[JAVA] 싱글톤 패턴 (Singleton Pattern) (0) | 2022.04.11 |
Google ARCore Sceneform archived 소식 (2) | 2020.05.30 |