• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with Unitialized Fields  RSS feed

 
Aahan Agrawal
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My code's objective is to serialize and deserialize to a file. I'm in the process of revising the code to allow multiple serializations and deserializations, but for now the code's limited to one serialization and deserialization. I'm also debugging one error, before I debug several others. I've limited my debugging question by accessing the field of one deserialization.

This is the code on pastie:
http://pastie.org/9507415

Could someone tell me how to display the code on coderanch? I don't understand how to use the code widget.


I can successfully serialize an object, but I cannot deserialize it and access its fields. If you execute the program, create a new file, add ONE FullTimeEmployee object to the file and then read its firstName field, you'll be returned null.

I'm certain I initialized the field by using a constructor. I'm also pretty sure that I correctly casted Object (if I'm not mistaken,the generic type for a deserialization) into FullTimeEmployee
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Find the code button, and that allows you to copy and paste the code. You can write the code then add code tags, or vice versa. The link shows an example of what the code should look like.

I think you have misunderstood serialisation. You convert the object to a series (hence the name) of bytes, which can be sent across a network or written into an object file. Any static members are not considered members of the object, so they are omitted from serialised objects, as are any fields marked transient, e.g. passwords.
you should simply write the object to a file. No getting fields at this stage. The object should be completely initialised before you try serialisation. The simplest way is for the class to have methods for serialisation. You can set up an object output stream and use its method, which looks something like this:-
objOutStream.writeObject(this);
The simplest way to deserialise an object file is to put a method in the class to return it:-
return (Person)objInputStream.readObject();
Note that you may have to use that method before there are any instances of that class available, so such a method is usually static. You will also need the usual Exception handling and your classes have to the Serializable interface.

There are lots more things you can do, with readResolve() and similar methods. Read about it in Bruce Eckel's book Thinking in Java and many other places.

I believe you should never have uninitialised fields anywhere. Initialise every field in every class you write by the time the constructor has completed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!