quilt code
[고급자바] IO (4) 본문
부모 클래스가 Serializable 인터페이스를 구현하고 있지 않을 경우 부모객체의 필드값 처리 방법 |
1. 부모 클래스가 Serializable 인터페이스를 구현하도록 한다. 2. 자식 클래스에 writeObject()와 readObject()메소드를 이용하여 부모객체의 필드값을 처리할 수 있도록 직접 구현한다. |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package kr.or.ddit.basic;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class T16NonSerializableParentTest {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
ObjectOutputStream oos =
new ObjectOutputStream(
new FileOutputStream("d:/D_Other/nonSerial.bin"));
Child child = new Child();
child.setParentName("부모");
child.setChildName("자식");
oos.writeObject(child); // 직렬화
oos.flush(); // 생략가능
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/D_Other/nonSerial.bin"));
Child child2 = (Child) ois.readObject(); // 역직렬화
System.out.println("parentName : " + child2.getParentName());
System.out.println("childName : " + child2.getChildName());
ois.close();
}
}
|
cs |
1. Serializable을 구현하지 않은 부모 클래스
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Parent { //부모를 serializable 하면 p,c 둘다 가능
private String parentName;
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
}
|
cs |
3. Serializable을 구현한 자식 클래스
|
1
2
3
4
5
6
7
8
9
10
|
class Child extends Parent implements Serializable {
private String childName;
public String getChildName() {
return childName;
}
public void setChildName(String childName) {
this.childName = childName;
}
|
cs |
|
1
2
3
4
5
6
7
8
9
10
11
12
|
/**
* 직렬화 될 때 자동으로 호출됨.
* (접근 제한자가 private이 아니면 자동호출 되지 않음)
* @param out
* @throws IOException
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeUTF(getParentName());
out.defaultWriteObject();
}
|
cs |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/**
* 역직렬화 될 때 자동으로 호출됨.
* (접근 제한자가 private이 아니면 자동 호출되지 않음)
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
setParentName(in.readUTF());
in.defaultReadObject();
}
|
cs |
'daily > 고급자바' 카테고리의 다른 글
| [고급자바] 람다 (0) | 2023.02.14 |
|---|---|
| [고급자바] IO (3) (0) | 2023.02.13 |
| [고급자바] IO (2) (0) | 2023.02.13 |
| [고급자바] IO (1) (0) | 2023.02.13 |
| [고급자바] Thread(6) (0) | 2023.02.13 |