有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

假设我有一个这样的类:

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代码反序列化回类


共 (1) 个答案

  1. # 1 楼答案

    官方的方法似乎是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;
    }
    

    据我所知,有必要在这里指定属性名,即使它对应于参数

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