无法在jaxb中解组阴影类变量 [英] Unable to unmarshal shadow class variable in jaxb
问题描述
@XmlSeeAlso(Employee.class)
public abstract class Person {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee extends Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在我的公共静态main()中,我setName (John)并将其编组为xml。
and in my public static main(), i setName("John") and marshal it to an xml.
这会生成一个XML: -
This generates an XML :-
<Employee>
<name>John</John>
</Employee>
但是,当我将其解组到Employee对象时,super和local类都没有名称变量初始化为'约翰'。我怀疑它为继承类和父类共享同名变量。我知道这是不好的做法,但是怎么可以解雇员工类呢?或两者?
However, when i unmarshal this to the Employee object, neither the super nor local class had their name variable initialized to 'John'. I suspect its the sharing of the same name variable for both the inherited and parent class. I understand that this is bad practice, however how can one unmarshal to the Employee class? or Both?
谢谢你。
推荐答案
回答这个问题从基本的java主体开始。由于派生类重写setName和getName。 (new Employee())。setName(John)填充Employee的名称而不是Person的名称。因此,如果要填充这两个类的属性,则应将person类更改为
Answer to this question starts from basic java principal. Since derived class override setName and getName . (new Employee()).setName("John") populates Employee's name not Person's. So if you want to populate properties of both the classes you should change person class to
@XmlSeeAlso(Employee.class)
public abstract class Person {
protected String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
并做元帅。
Employee e = new Employee();
e.setName("John");
e.setLastName("JohnLast");
然后你的xml看起来像
then your xml will look like
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<lastName>JohnLast</lastName>
<name>John</name>
</employee>
和xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="employee" type="employee"/>
<xs:complexType name="employee">
<xs:complexContent>
<xs:extension base="person">
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="person" abstract="true">
<xs:sequence>
<xs:element name="lastName" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
并且在解组后的工作和名称和lastName被填充,
and during unmarshalling following works and name and lastName gets populated,
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employee e = (Employee) unmarshaller.unmarshal(xml);
Person p = (Person) unmarshaller.unmarshal(xml);
这篇关于无法在jaxb中解组阴影类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!