【发布时间】:2018-06-27 13:19:25
【问题描述】:
我的应用程序从另一个应用程序接收以下形式的 xml:
<targetedMessage>
<sender>the sender</sender>
<payload class="other.app.classpath.Foo">
<id>1</id>
</payload>
</targetedMessage>
其中Foo 是我的模块和其他应用程序中存在的几个类中的任何一个,并实现了一个通用接口:
@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class Foo implements MyInterface {
private long id;
\\ getters and setters
}
TargetedMessage 类是:
@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class TargetedMessage {
private String sender;
private MyInterface payload;
\\ getters and setters
}
我有一个枚举,它将其他应用程序的类路径映射到我的模块中的类:
public enum MyClasses {
FOO(Foo.class, "other.app.classpath.Foo"),
BAR(Bar.class, "other.app.classpath.Bar"),
\\ ...
}
使用 JAXB,是否可以解组 xml 以使有效负载具有正确的类型(在上述情况下,有效负载类将为 Foo)。
【问题讨论】:
-
这是可能的,但您需要定义一个可以包含任何 MyInterface 实现内容的类。我不想写答案,请参阅dzone.com/articles/jaxb-and-inhertiance-using
标签: java xml jaxb unmarshalling xml-attribute