@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;
}
}
并在我的public static main()中,我setName(“John”)并将其编组为xml。
这会生成一个XML: -
<Employee>
<name>John</John>
</Employee>
但是,当我将其解组到Employee对象时,super和local类的名称变量都没有初始化为'John'。我怀疑它为继承类和父类共享同名变量。我知道这是不好的做法,但是怎么可以解雇员工类呢?还是两个?
谢谢你。
答案 0 :(得分:0)
这个问题的答案从基本的java主体开始。由于派生类重写setName和getName。 (new Employee())。setName(“John”)填充Employee的名称而不是Person的名称。因此,如果要填充两个类的属性,则应将人员类更改为
@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看起来像
<?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被填充,
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employee e = (Employee) unmarshaller.unmarshal(xml);
Person p = (Person) unmarshaller.unmarshal(xml);