在kotlin中使用@XmlElement不起作用

owl*_*owl 4 java annotations jaxb kotlin

当我序列化一个类的实例时ReturnValue,我发现它@XmlElement不起作用.生成的xml仍然有一个标签<summary>,而不是<comment>.

ReturnValue类:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
                       @XmlElement(name="comment")
                       val summary: String){
    constructor(): this(type="java.lang.Object", summary="no summary")
} 
Run Code Online (Sandbox Code Playgroud)

测试程序:

fun main(args: Array<String>) {
    val jaxbContext = JAXBContext.newInstance(ReturnValue::class.java)
    val marshaller = jaxbContext.createMarshaller()
    marshaller.marshal(
        ReturnValue(type = "java.lang.Object",summary = "hello"),
        System.out)
}
Run Code Online (Sandbox Code Playgroud)

和输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><returnValue><type>type2</type><summary>hello</summary></returnValue>
Run Code Online (Sandbox Code Playgroud)

所以,我想换<summary><comment>.我怎样才能做到这一点?

Jes*_*per 9

JAXB是一个Java API,它希望事物看起来像Java通常做的事情,而Kotlin做的事情略有不同.

要注释参数以使其看起来对JAXB正确,您必须使用@field:XmlElement以便将注释放在Kotlin参数转换为的Java字段上,如下所示:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
                       @field:XmlElement(name = "comment") val summary: String) {
  constructor() : this(type = "java.lang.Object", summary = "no summary")
}
Run Code Online (Sandbox Code Playgroud)

更多信息:Kotlin文档中的注释使用站点目标.