在 JAXB 解组期间自动生成字段值

Autogenerate a field value during JAXB unmarshalling

说,我有一个 XML 如下:

<MyBooks>
    <book>
        <author>some author</author>
        <name>Book A</name>
    </book>
    <book>
        <author>some other author</author>
        <name>Book B</name>
    </book>
</MyBooks>

.....我想要一个这样的 class 来代表每个 book:

class Book{
    String id;
    String author;
    String name;
}

在使用 JAXB 时,我们能否为每个书籍对象的 "id" 字段设置一个自动生成的唯一 ID...在解组过程中? (我不希望 XML 的供应商承受为 XML 中的每本书添加一个 "id" 的痛苦。

在您的 Book class 中实施此方法。用它来创建你想要的 id。 (不是接口的一部分,只是匹配签名)

 //This method is called after all the properties (except IDREF) are unmarshalled for this object,
 //but before this object is set to the parent object.
 void afterUnmarshal(Unmarshaller, Object parent);