However, we can externally make these variables available in serialized object in following way.
class Animal implements Serializable {
transient int legs, wings;
private void writeObject(ObjectOutputStream os) {
try {
os.defaultWriteObject();
os.writeInt(legs);
os.writeInt(wings);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
// swapped:
this.wings = is.readInt();
this.legs = is.readInt();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
------------------
public class AnimalSerializer { public static void main(String[] args) {
List list = new ArrayList();
Animal bird = new Animal("Bird", 2, 2);
Animal fly = new Animal("Fly", 6, 2);
list.add(bird);
list.add(fly);
try {
FileOutputStream fos = new FileOutputStream("anis.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(list);
list = null;
System.out.println(list);
try {
FileInputStream fis = new FileInputStream("anis.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
list = (List) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(list);
}
}
No comments:
Post a Comment