1

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?

Is XmlElement annotation,
annotation.type != javax.xml.bind.annotation.XmlElement.DEFAULT.class
the only case I need to worry about?

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.

Thanks.

--Update--

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";
  }
}

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?

Mike Summers
  • 2,139
  • 3
  • 27
  • 57

1 Answers1

2

There are a couple circumstances where a JAXB (JSR-222) implementation will write out an xsi:type attribute.

  1. 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.
  2. 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).
kapex
  • 28,903
  • 6
  • 107
  • 121
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Thanks Blaise. Case #2 is what I'm interested in, how do I detect inheritance? Is there something in the annotations or do I need to look elsewhere? – Mike Summers Aug 24 '12 at 16:11
  • @Mike - There isn't a standard way that would work across JAXB implementations. If you provide more info on what you are trying to map I maybe able to help that way. I'm pretty familiar with JAXB and inheritance: http://blog.bdoughan.com/search/label/Inheritance) – bdoughan Aug 24 '12 at 17:42
  • sorry for the reply delay. We're using the reference implementation from Oracle. My work around is recursively building the annotation map through superclasses, so far this works. It would be handy to be able to ask an annotation what types it expects though. I'll try and come-up with simple example and post it. Thanks for your time. – Mike Summers Aug 31 '12 at 15:26