Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Serialization

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi all, question for ya...

I'm working on a program with the ability to save an array of objects, and inside the class for the objects is a static counter for the number of objects created. How can I serialize this data, and reload it after?

Any Ideas??
 
Your serializable object has to have a no-argument contructor. If you put code in that constructor to add 1 to the counter, then when your array is reconstituted the counter should increment right back up to the correct value.

I haven't tried this ... post back if it works.

Cheers
 
Hi Cr@kv1ct1m,
I'm sorry to say this, but it is the fact that what you wish to do is impossible.
Using the technique of serialization, you can make persistent only data that belong to the objects. When you declare a variable to be static, then it becomes a class definition and thus you loose the right of serializing it. Another type of variable that cannot be serialized is the transient variable.
To get into a little more deeper, the memory for the static variables will be allocated separately (not in the memory area of the object instances) and this will be commonly shared by all the object instances.

Regards,
Rajarajan
 
I agree that the value of the static variable will be lost. The variable itself will be reconstituted with the default initial value.

What would probably be easiest is to create another small class that merely holds the value of the static variable.

public class Counter implements Serializable
{
private Integer save;

public Counter( int counter )
{
save = new Integer( counter );
}

public Counter() {}

public int getValue() { return save.intValue(); }
}

Pop the value of the variable in this small class and serialize it along with the array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top