You could do the following.
Note:
- It does not require that you ever materialize the data as XML, by leveraging JAXBSource.
- It does not require any annotations on your object model.
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 code;
Status(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
com.school.Student
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 code;
Status(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
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());
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…