serialization - Java trouble serializing a field of an object -
i'm trying learn serialization , encountered following problem:
i have implementation of customer looks this.
private static customercount = 0; private string customerid; private string name; private string street; private string city; private string postcode; private string type;
i'm trying serialize / deserialize arraylist
in constructor, id created this:
private customer(...){ this.customerid = "id" + customercount; customercount++; }
the serialization process works, however, ids set id0
when deserialize. can resolve problem?
update: alright, found out static fields wont serialized. how can "model" id of customer can serialize it? need have unique value create ids customers.
here's solution combines factory list keeps track of customer count.
the customer class has protected constructor, forcing build them through means within same package.
public class customer implements serializable { private string customerid; private string name; private string street; private string city; private string postcode; private string type; protected customer(string customerid, string name, string street, string city, string postcode, string type) { this.customerid = customerid; this.name = name; this.street = street; this.city = city; this.postcode = postcode; this.type = type; } }
now within package, create list wrapper this:
public class customerlist { private int customercount = 0; private list<customer> customers = new arraylist<>(); public boolean addcustomer(string name, string street, string city, string postcode, string type) { customer customer = new customer("id" + customercount++, name, street, city, postcode, type); return customers.add(customer); } }
this class takes care of constructing new customer, , provides unique id.
edit: noticed have upside of making customerlist class serializable well. can load , still have accurate customer count adding additional uniquely id-ed customers.
Comments
Post a Comment