JAXB不解组接口列表

时间:2012-06-20 20:40:25

标签: java xml jaxb

似乎JAXB无法读取它所写的内容。请考虑以下代码:

interface IFoo {
    void jump();
}

@XmlRootElement
class Bar implements IFoo {
    @XmlElement
    public String y;

    public Bar() {
        y = "";
    }

    public Bar(String y) {
        this.y = y;
    }

    @Override
    public void jump() {
        System.out.println(y);
    }
}

@XmlRootElement
class Baz implements IFoo {
    @XmlElement
    public int x;

    public Baz() {
        x = 0;
    }

    public Baz(int x) {
        this.x = x;
    }

    @Override
    public void jump() {
        System.out.println(x);
    }
}

@XmlRootElement
public class Holder {
    private List<IFoo> things;

    public Holder() {
        things = new ArrayList<>();
    }

    @XmlElementWrapper
    @XmlAnyElement
    public List<IFoo> getThings() {
        return things;
    }

    public void addThing(IFoo thing) {
        things.add(thing);
    }
}

// ...

try {
    JAXBContext context = JAXBContext.newInstance(Holder.class, Bar.class, Baz.class);

    Holder holder = new Holder();
    holder.addThing(new Bar("1"));
    holder.addThing(new Baz(2));
    holder.addThing(new Baz(3));

    for (IFoo thing : holder.getThings()) {
        thing.jump();
    }

    StringWriter s = new StringWriter();
    context.createMarshaller().marshal(holder, s);

    String data = s.toString();

    System.out.println(data);

    StringReader t = new StringReader(data);
    Holder holder2 = (Holder)context.createUnmarshaller().unmarshal(t);

    for (IFoo thing : holder2.getThings()) {
        thing.jump();
    }
}
catch (Exception e) {
    System.err.println(e.getMessage());
}

当然,这是一个简化的例子。关键是我必须在一个集合中存储两个非常不同的实现类Bar和Baz。好吧,我观察到他们有非常相似的公共接口,所以我创建了一个接口IFoo并使它们实现它。现在,我想要有工具来保存和加载这个集合到XML或从XML加载。不幸的是,这段代码不太有效:集合已保存,但无法加载!预期的输出是

1
2
3
some xml
1
2
3

但不幸的是,实际输出是

1
2
3
some xml
com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to testapplication1.IFoo

显然,我需要以不同的方式使用注释?或者放弃JAXB并寻找其他东西?我可以为所有我不想(de)编组的类编写“XMLNode toXML()”方法,但是......

1 个答案:

答案 0 :(得分:9)

尝试以下@XmlAnyElement(lax=true)lax标志告诉JAXB(JSR-222)实现根据其@XmlRootElement@XmlElementDecl注释将元素与域对象匹配。没有它,内容将被视为DOM节点。

@XmlRootElement
public class Holder {
    private List<IFoo> things;

    public Holder() {
        things = new ArrayList<>();
    }

    @XmlElementWrapper
    @XmlAnyElement(lax=true)
    public List<IFoo> getThings() {
        return things;
    }

    public void addThing(IFoo thing) {
        things.add(thing);
    }
}

了解更多信息