使用简单XML框架反序列化不可变类

问题描述 投票:0回答:1

假设我有这样的课程:

public class Measurement {
    /** The date and time at which the measurement was taken. */
    public final Date date;

    /** The measurement value. */
    public final float value;

    /** The name of the engineer who took the measurement. */
    public final String engineer;

    public Measurement(Date date, float value, String engineer) {
        super();
        this.date = date;
        this.value = value;
        this.engineer = engineer;
    }
}

每个Measurement实例是不可变的。创建后,其成员无法修改。但是,可以创建一个新实例,其中一些值是从现有实例中复制的,而某些值则设置为不同。

如果情况变得更复杂,例如因为存在大量字段,并且其中大多数字段不是强制性的,所以构造函数将是私有的,而该类将带有一个builder类。 (实际上,实际代码更复杂;这只是一个最小的示例。)

现在,我可以很容易地添加一些SimpleXML注释,以将其序列化为XML,如下所示:

@Root(name="measurement")
@Default
public class Measurement {
    /** The date and time at which the measurement was taken. */
    @Attribute
    public final Date date;

    /** The measurement value. */
    @Attribute
    public final float value;

    /** The name of the engineer who took the measurement. */
    @Attribute
    public final String engineer;

    public Measurement(Date date, float value, String engineer) {
        super();
        this.date = date;
        this.value = value;
        this.engineer = engineer;
    }
}

然后将序列化为类似内容:

<measurement date="2019-11-01 11:55:42.0 CET" value="42.0" engineer="Doe"/>

然后我将如何将生成的XML代码反序列化回一个类?

java xml-deserialization simple-framework
1个回答
0
投票

官方的方法似乎是constructor injection:设置最终成员的唯一方法是通过构造函数,构造函数为每个成员都有一个参数。因此,构造函数将如下所示:

public Measurement(@Attribute(name="date") Date date,
                   @Attribute(name="value") float value,
                   @Attribute(name="engineer") String engineer) {
    super();
    this.date = date;
    this.value = value;
    this.engineer = engineer;
}

不确定与参数对应的属性名称是否真的必要。

在示例中,构造函数是公共的。大概必须从Persister类可以访问它。

© www.soinside.com 2019 - 2024. All rights reserved.