【发布时间】: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