您可以执行以下操作。
注意:
- 不需要利用JAXBSource将数据具体化为XML。
- 它在对象模型上不需要任何注释。
com.home.Student
package com.home;public class Student { private String name; private Status status; public String getName() { return name; } public void setName(String name) { this.name = name; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; }}com.home.Status
package com.home;public enum Status { FULL_TIME("F"), PART_TIME("P"); private final String pre; Status(String pre) { this.pre = pre; } public String getCode() { return pre; }}普通学校学生
package com.school;public class Student { private String name; private Status status; public String getName() { return name; } public void setName(String name) { this.name = name; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; }}com.school.Status
package com.school;public enum Status { FULL_TIME("F"), PART_TIME("P"); private final String pre; Status(String pre) { this.pre = pre; } public String getCode() { return pre; }}com.example.Demo;
package com.example;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBElement;import javax.xml.bind.Unmarshaller;import javax.xml.bind.util.JAXBSource;import javax.xml.namespace.QName;public class Demo { public static void main(String[] args) throws Exception { com.home.Student studentA = new com.home.Student(); studentA.setName("Jane Doe"); studentA.setStatus(com.home.Status.FULL_TIME); JAXBContext contextA = JAXBContext.newInstance(com.home.Student.class); JAXBElement<com.home.Student> jaxbElementA = new JAXBElement(new QName("student"), com.home.Student.class, studentA); JAXBSource sourceA = new JAXBSource(contextA, jaxbElementA); JAXBContext contextB = JAXBContext.newInstance(com.school.Student.class); Unmarshaller unmarshallerB = contextB.createUnmarshaller(); JAXBElement<com.school.Student> jaxbElementB = unmarshallerB.unmarshal(sourceA, com.school.Student.class); com.school.Student studentB = jaxbElementB.getValue(); System.out.println(studentB.getName()); System.out.println(studentB.getStatus().getCode()); }}


