JAXB Unmarshal 泛型对象

JAXB Unmarshal generic object

我是 JAXB 的新手,在尝试解组通用对象时遇到了问题。问题是我需要能够编组和解组任何对象 (java.lang.Object)。我成功执行了 marshal,但是当我 运行 unmarshal 时,我在响应中得到一个 "ElementNSImpl" 对象,而不是我自己的对象。
这是涉及的bean:
Message.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Message {
    @XmlAnyElement(lax=true)
    private Object obj;
    //getter and setter
}


SomeBean.java

@XmlRootElement(name="somebean")
public class SomeBean {
    private String variable;
    //getter and setter
}

这是 marshal/unmarshal

的代码
Message m = new Message();
SomeBean sb = new SomeBean();
sb.setVariable("lalallalala");
m.setObj(sb);

JAXBContext jaxbContext = JAXBContext.newInstance("jaxb.entities");
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(m, sw);
System.out.println(sw.toString());  //this shows me the xml correctly

//unmarshal code
JAXBContext jc = JAXBContext.newInstance(Message.class);
StringReader reader = new StringReader(sw.toString());
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object result = unmarshaller.unmarshal(reader);
Message msg = (Message)result;


jaxb.index的内容:

Message
SomeBean

生成的xml很好(<?xml version="1.0" encoding="UTF-8" standalone="yes"?><message><somebean><variable>lalallalala</variable></somebean></message>)但是当我在解组后评估"msg.getObj()"时,我没有得到一个SomeBean实例,而是一个ElementNSImpl。
所以,我的问题是,如何才能取回已编组的 SomeBean 对象?
提前致谢。

终于用这个答案解决了它:,我应用了两次解组:

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Object result = unmarshaller.unmarshal(reader);
    Message msg = (Message)result;
    if (msg.getObj() instanceof Node) {
        ElementNSImpl e = (ElementNSImpl)msg.getObj();
        Class<?> clazz = Class.forName(packageName.concat(".").concat(e.getNodeName()));
        jc = JAXBContext.newInstance(clazz);
        unmarshaller = jc.createUnmarshaller();
        SomeBean sBean = (SomeBean)unmarshaller.unmarshal((ElementNSImpl)msg.getObj());
        System.out.println(sBean.toString());
    }