以编程方式确定JAXB注释是否会导致xsi:type注释? [英] Programmatically determine if a JAXB annotation will result in a xsi:type annotation?
问题描述
反思JAXB带注释的对象,有没有办法确定类/字段/方法是否会在编组期间产生xsi:type属性?
Reflecting on JAXB annotated objects, is there a way to determine if a class/field/method will result in a xsi:type attributed during marshaling?
是否为XmlElement注释,
annotation.type!= javax.xml.bind.annotation.XmlElement.DEFAULT.class
唯一的案例我需要担心吗?
Is XmlElement annotation,
annotation.type != javax.xml.bind.annotation.XmlElement.DEFAULT.class
the only case I need to worry about?
我正在写一个Lua unmarshaler,我们已经删除了大部分通常的xml类型信息,我正在试图弄清楚如何将传入的Lua与JAXB匹配。
I'm writing a Lua unmarshaler where we have dropped much of the usual xml type info and I'm trying to figure-out how to match the incoming Lua to JAXB.
谢谢。
- 更新 -
以下是显示问题的简单示例:
Here is simple example that shows the problem:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement()
@XmlSeeAlso({ Cat.class, Dog.class })
public class Animal {
@XmlElement()
public List<Animal> critters;
@XmlAttribute
public String type;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement()
public class Dog extends Animal {
public Dog() {
this.type = "German Shepherd";
}
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement()
public class Cat extends Animal {
public Cat() {
this.type = "Black";
}
}
当我收到Animal对象时,我可以查询生物的注释检测它应该是狗还是猫而不是动物?
When I receive an Animal object can I query critter's annotation to detect that it should be a Dog or Cat and not an Animal?
推荐答案
有几种情况下 JAXB(JSR-222) 实现将写出xsi:类型属性。
There are a couple circumstances where a JAXB (JSR-222) implementation will write out an xsi:type attribute.
- 如果字段/属性的类型为
对象
(或者是用@XmlElement(type = Object.class)注释并且没有用
@XmlAnyElement(lax = true)映射并保存一个Object的实例
JAXBContext`有映射。 - 表示继承的默认机制将导致
xsi:type
属性表示子类(请参阅: http:// blog .bdoughan.com / 2010/11 / JAXB和继承-USI NG-xsitype.html )。
- If the field/property is of type
Object
(or is annotated with@XmlElement(type=Object.class)) and not mapped with
@XmlAnyElement(lax=true)and holds an instance of an Object that the
JAXBContext` has mappings for. - The default mechanism for representing inheritance will result in an
xsi:type
attribute to represent subclasses (see: http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html).
这篇关于以编程方式确定JAXB注释是否会导致xsi:type注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!