问题
I have class hierarchy
interface Intf {}
Class A implements Intf{}
Class B implements Intf{}
Now I am using above Class A and Class B to read two diffrent XML files with the elp of JaxB. Can any one suggest me how to configure and use structure like above in JaxB?
回答1:
For your use case the interface doesn't factor in. If you want to map A and B to different XML structures you can go ahead and do so, I'll demonstrate below with an example.
JAVA MODEL
IntF
public interface IntF {
public String getFoo();
public void setFoo(String foo);
}
A
import javax.xml.bind.annotation.*;
@XmlRootElement
public class A implements IntF {
private String foo;
@Override
@XmlElement(name="renamed-foo")
public String getFoo() {
return foo;
}
@Override
public void setFoo(String foo) {
this.foo = foo;
}
}
B
import javax.xml.bind.annotation.*;
@XmlRootElement
public class B implements IntF {
private String foo;
@Override
@XmlAttribute
public String getFoo() {
return foo;
}
@Override
public void setFoo(String foo) {
this.foo = foo;
}
}
DEMO CODE
Demo
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class, B.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
A a = new A();
a.setFoo("Hello World");
marshaller.marshal(a, System.out);
B b = new B();
b.setFoo("Hello World");
marshaller.marshal(b, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8"?>
<a>
<renamed-foo>Hello World</renamed-foo>
</a>
<?xml version="1.0" encoding="UTF-8"?>
<b foo="Hello World"/>
来源:https://stackoverflow.com/questions/15676401/parsing-class-hierarchy-using-jaxb