【问题标题】:Deserialize immutable class with Simple XML framework使用简单 XML 框架反序列化不可变类
【发布时间】:2020-03-13 05:05:50
【问题描述】:

假设我有这样的课程:

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 实例都是不可变的。一旦创建,它的成员就不能被修改。但是,可以创建一个新实例,其中一些值从现有实例中复制而来,而另一些则设置不同。

如果事情变得更复杂,例如因为有大量字段并且其中大多数不是强制性的,所以构造函数将是私有的,而该类将伴随着一个构建器类。 (实际上,实际代码更复杂;这只是一个小例子。)

现在我可以很容易地添加一些 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】:

官方的做法似乎是constructor injection:设置final成员的唯一方法是通过构造函数,构造函数对每个成员都有一个参数。所以构造函数看起来像这样:

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;
}

据我所知,这里需要指定属性名,即使对应的是参数。

在示例中,构造函数是公共的。不确定这里需要什么,因为 SimpleXML 似乎依赖反射来找到正确的构造函数。

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2010-12-27
    • 1970-01-01
    • 2018-01-23
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多