Please take a look at the following example. I got the exception that XmlIDREF annotation is not allowed in class Bar. If you use the concrete Class Bar instead of IBar it works perfectly. But i have to use the interface. Is there a solution for this problem?
@XmlRootElement
public class Foo {
@XmlElement(name = "bar")
public List<Bar> bars;
public String fooProp;
}
public interface IBar {
@XmlID
String getId();
void setId(String id);
}
@XmlRootElement
public class Bar implements IBar {
@XmlIDREF
@XmlAnyElement
public IBar bar;
public String barProp;
private String id;
@Override
@XmlID
public String getId() {
return this.id;
}
@Override
public void setId(String id) {
this.id = id;
}
}
public static void main(String[] args) throws Exception {
File file = null;
file = new File("somewhere");
try(Writer w = new FileWriter(file)){
JAXBContext context = JAXBContext.newInstance("jaxbtest");
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
Foo foo = new Foo();
foo.fooProp ="FooProperty";
Bar bar1 = new Bar();
bar1.barProp = "BarProperty1";
bar1.setId("1");
Bar bar2 = new Bar();
bar2.barProp = "BarProperty2";
bar2.setId("2");
bar1.bar = bar2;
bar2.bar = bar1;
List<Bar> list = new ArrayList<Bar>();
list.add(bar1);
list.add(bar2);
foo.bars = list;
m.marshal(foo, w);
} catch (Exception e) {
e.printStackTrace();
}
}