Java 序列化对象字段时遇到问题

标签 java serialization

我正在尝试了解序列化并遇到以下问题:

我有一个客户的实现,看起来有点像这样。

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/

相关文章:

java - 如何在scala akka中找到父 Actor

Java项目布局——能简单点吗?

c# - 将 json 反序列化为包含字典的强类型对象

java - JAXB 父类(super class)字段未反序列化

java - 如何序列化包含java中对象的对象?

java - 使用 WPA 密码的所有允许的 ASCII 字符填充 java 数组

java - 用户在数组中输入 10 个数字,我该如何编写代码来查找该数字并输出它在数组中的位置?

objective-c - 如何将 JSON 对象映射到 Objective C 类?

java - com.google.gson.JsonSyntaxException : java. lang.IllegalStateException:应为 BEGIN_ARRAY 但为 STRING

java - 无法使用 ExecutorService 和 Callables 捕获特定异常?