2 classes DOG and Collar
狗有一个不可序列化的项圈
Collar 有 String 和 int
问题:如何序列化 DOG 对象?尝试覆盖 writeObject 和 readObject 但在写入领子的 String 成员时卡住了如何编写和读取它?
这是2个班
import java.io.*;
public class Dog implements Serializable{
String name;
transient Collar c;
public Dog(String name, Collar c){
this.name = name;
this.c =c;
}
public static void main(String args[]){
Dog d = new Dog("DogsName",new Collar("CollarsColor",3));
try {
File f = new File("dogs.ser");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Dog d2 =(Dog)ois.readObject();
System.out.println(d2);
ois.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Collar {
String color;
int size;
public Collar(){
color= "White";
size =10;
}
public Collar(String c,int s){
color =c;
size =s;
}
}