主页 > 人工智能  > 

JAXB的XmlElement注解

JAXB的XmlElement注解
依赖 如果基于JAX-WS开发,可以在maven工程的pom.xml文件中增加如下依赖,会将依赖的JAXB库也下载下来: <dependency> <groupId>jakarta.xml.ws</groupId> <artifactId>jakarta.xml.ws-api</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>jaxws-rt</artifactId> <version>4.0.0</version> </dependency> 如果只想使用JAXB库,可以在maven工程的pom.xml文件中增加如下依赖: <dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>4.0.3</version> </dependency> XmlElement注解使用说明 XmlElement注解可以用在Java的属性上

备注: 如果XmlElement注解用在Java的属性上,该属性就不能出现getter和setter方法,否则运行出错

例如,下面片段XmlElement注解的属性name = "flag"指定了映射到xml中元素的名字是flag。如果不指定,xml元素的名字就会是functionCode:

@XmlElement(name = "flag") private int functionCode; XmlElement注解可以用在属性的getter方法上

例如:

@XmlElement(name = "flag") public int getFunctionCode() { return this.functionCode; }

我感觉这种方法是灵活的,原因:

XmlElement注解用在属性的getter方法上,既能够修改映射到xml中的元素的名称,也方便在代码中设置属性。因为如果类的属性很多的话,直接用构造函数感觉太长了。如果直接注解在属性上,尽管也可以修改映射到xml中的元素的名称,但设置属性的值就必须用类的构造函数,不太方便。原因就是如果映射到属性上,那么该类属性就不能出现getter和setter方法,否则运行出错。

例如,下面用在getFunctionCode()方法上,设置了了映射到xml中的元素名称是flag:

private int functionCode; @XmlElement(name = "flag") public int getFunctionCode() { return this.functionCode; } public void setFunctionCode(int functionCode) { this.functionCode = functionCode; }

在调用的地方设置属性的值:

RegisterResponse registerResponse = new RegisterResponse(); registerResponse.setFunctionCode(1); 如果 XmlElement注解用在属性上,同时类中有针对该属性的getter和setter方法,是会出错的

例如,下面这段代码,XmlElement注解用在属性functionCode上,同时,有针对functionCode的getFunctionCode和setFunctionCode方法,运行就会出错,提醒有两个属性具有相同的名称(为了突出重点,调用的代码没有贴出来):

package com.thb.server.register; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "response") public class RegisterResponse { @XmlElement(name = "flag") private int functionCode; public RegisterResponse() {} public int getFunctionCode() { return this.functionCode; } public void setFunctionCode(int functionCode) { this.functionCode = functionCode; } }

运行出错:

标签:

JAXB的XmlElement注解由讯客互联人工智能栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“JAXB的XmlElement注解