是否有可能使用@XmlElememts
来表示相同类型参数之间的选择。最好用一个例子来解释:
@XmlElements({
@XmlElement(name="dogId", type=Long.class),
@XmlElement(name="catId", type=Long.class)})
private Long animalId;
所以,当我收到id
时,我想知道它是狗还是猫。
解决方案1将是:
@XmlElement
private Long dogId;
@XmlElement
private Long catId;
虽然这是一个显而易见的解决方案,但我手动必须检查其中只有一个已设置,在我的情况下我更喜欢使用单个xml字段。
这会是一个很好的解决方案吗?
@XmlElements({
@XmlElement(name="dogId", type=CatId.class),
@XmlElement(name="catId", type=DogId.class)})
private Long animalId;
public class DogId extends BigInteger {
...
}
public class CatId extends BigInteger {
...
}
这个问题有标准解决方案吗?
答案 0 :(得分:0)
或者当你想知道你的动物的其他属性时,有时会发生这种情况
@XmlElements({
@XmlElement(name="dog", type=Dog.class),
@XmlElement(name="cat", type=Cat.class)})
private List<Animal> animals;
public class Animal {
// common animal properties
BigInteger id;
}
public class Dog extends Animal {
// dog specific properties
}
public class Cat extends Animal {
// cat specific properties
}
答案 1 :(得分:0)
我使用了以下解决方案:
@XmlElementRefs({
@XmlElementRefs(name="dogId", namespace = "animals.com", type = JAXBElement.class),
@XmlElementRefs(name="catId", namespace = "animals.com", type = JAXBElement.class)})
private JAXBElement<Long> animalId;
然后你还需要一个ObjectFactory
:
@XmlRegistry
public class ObjectFactory {
private final static QName CAT_ID_QNAME = new QName("animals.com", "catId");
private final static QName DOG_ID_QNAME = new QName("animals.com", "dogId");
public ObjectFactory() {
}
@XmlElementDecl(namespace = "animals.com", name = "catId", scope = AnimalsRequestXML.class)
public JAXBElement<Long> createCatId(final Long value) {
return new JAXBElement<>(CAT_ID_QNAME, Long.class, AnimalsRequestXML.class, value);
}
@XmlElementDecl(namespace = "animals.com", name = "dogId", scope = AnimalsRequestXML.class)
public JAXBElement<Long> createDogId(final Long value) {
return new JAXBElement<>(DOG_ID_QNAME, Long.class, AnimalsRequestXML.class, value);
}
这会生成xs:choice
:
<xs:choice>
<xs:element name="catId" type="xs:long"/>
<xs:element name="dogId" type="xs:long"/>
</xs:choice>