我正在尝试了解序列化并遇到以下问题:
我有一个客户的实现,看起来有点像这样。
private static customerCount = 0;
private String customerID;
private String name;
private String street;
private String city;
private String postcode;
private String type;
我正在尝试序列化/反序列化 Arraylist
在构造函数中,ID 将如下创建:
private Customer(...){
this.customerID = "ID" + customerCount;
customerCount++;
}
序列化过程有效,但是,当我反序列化时,所有 ID 都设置为 ID0
。
谁能帮忙解决这个问题吗?
更新:好吧,我刚刚发现静态字段不会被序列化。如何“建模”客户的 ID,以便将其序列化?我需要有一个独特的值来为客户创建 ID。
最佳答案
这是一个将工厂与跟踪客户数量的列表相结合的解决方案。
客户类有一个 protected 构造函数,迫使您在同一包中通过其他方式构建它们。
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;
}
}
现在在包中创建一个列表包装器,如下所示:
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);
}
}
该类负责构建新客户,并提供唯一的 ID。
编辑:刚刚注意到,您现在还拥有使 CustomerList 类可序列化的好处。然后您可以加载它,并且仍然拥有准确的客户计数,以便添加其他具有唯一 ID 的客户。
关于Java 序列化对象字段时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35039886/