aspose file tools*
The moose likes Beginning Java and the fly likes About serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "About serialization" Watch "About serialization" New topic
Author

About serialization

C Law
Greenhorn

Joined: Mar 05, 2006
Posts: 21
I'm not sure I understand how the state of an object is preserved.

For one thing:

Animal a = new Animal();
try{
FileOutputStream fo = new FileOutputStream("test.ser");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(a);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}

What is test.ser? Is it an actual file? How can I found it?

Secondly, it seems that I can modify instance variable after
the object containing it has been serialized:

public class Animal{
String name = "Mutsang";

public static void main(String[] argv){
Animal a = new Animal();
try{
FileOutputStream fo = new FileOutputStream("test.ser");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(a);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}

a.name = "Tiger";

try{
FileInputStream fi = new FileInputStream("test.ser");
ObjectInputStream oo = new ObjectInputStream(fi);
oo.readObject();
System.out.println(a.name);
oo.close();
}
catch(IOException ex){
ex.printStackTrace();
}
//output is Tiger.

If the state is really saved in "test.ser", how come that when
the object is restored, its "name" field is changed?

Thanks in advance!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18707
    
  40

Hint: When you run this command...



What do you think happens to the object that is returned?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About serialization