본문 바로가기
Java/Java with Error

[해결 방법] java.io.NotSerializableException

by HJ0216 2023. 2. 17.

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

package io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ObjectMain {
	public static void main(String[] args) throws IOException {
		PersonDTO pDTO = new PersonDTO("홍길동", 25, 185.3);
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("result.txt"));
		oos.writeObject(pDTO);
		oos.close();
		
	}
}

java.io.NotSerializableException 발생

 

 

Exception 원인

입출력 처리 시, Object(객체)는 파일이나 네트워크로 전송이 되지 않음

객체를 byte[]화하여, 전송해야 함(Serializable)

 

 

해결 방법

Object type인 PersonDTO class에서 Serializable interface 구현

package io;

import java.io.Serializable;

public class PersonDTO implements Serializable { // abstract method X

	private String name;
	private int age;
	private double height;

	public PersonDTO(String name, int age, double height) {
		this.name = name;
		this.age = age;
		this.height = height;
	}
	
	public void setName(String name) {this.name = name;}
	public void setAge(int age) {this.age = age;}
	public void setHeight(double height) {this.height = height;}
	
	public String getName() {return name;}
	public int getAge() {return age;}
	public double getHeight() {return height;}
	
}
package io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ObjectMain {
	public static void main(String[] args) throws IOException {
		PersonDTO pDTO = new PersonDTO("홍길동", 25, 185.3);
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("result.txt"));
		oos.writeObject(pDTO);
		oos.close();
		
	}
}

/*
Result
Name: 홍길동
Age: 25
Height: 185.3
*/