How to tell only certain Classes in XSD to inheirt from a provided interface?

1k views Asked by At

I have found some other questions that ask this in a different way, but none of the answers to those questions work. Either the sites they refer to are dead or they are not for JAXB2.

What I need is for more than a few of the generated classes to inherit from a common interface because they all have a .getName() method.

Rather than have to have a huge if(o instanceof XXX) for each of the types, block I would rather just test against this common Interface by casting to it and calling .getName().

Here is my interface

package com.mycompany;

public interface Nameable
{
    public String getName();
}

and here is what I am adding to my .xjb bindings file

<jxb:bindings version="2.1"
          xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
          xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
          xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
          xmlns:inheritance="http://jaxb2-commons.dev.java.net/basic/inheritance"
          jxb:extensionBindingPrefixes="xjc inheritance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"

...

<jxb:bindings node="//xsd:element[@name='container']">
  <inheritance:implements>com.mycompany.Nameable</inheritance:implements>
</jxb:bindings>

It isn't adding anything to the generated classes.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "contents"
})
@XmlRootElement(name = "container")
public class Container implements Cloneable, CopyTo, Equals, HashCode, MergeFrom, ToString
{
   ...
}

What is the magical incantation to get this interface added to the list?

2

There are 2 answers

0
AudioBubble On BEST ANSWER
<jxb:bindings node="//xsd:element[@name='container']">
  <inheritance:implements>com.mycompany.Nameable</inheritance:implements>
</jxb:bindings>

needed to look like

<jxb:bindings node="//xsd:element[@name='container']">
  <jxb:class/>
  <inheritance:implements>com.mycompany.Nameable</inheritance:implements>
</jxb:bindings>

once I added the missing stanza it started working as expected

0
lexicore On

I think you should customize the complex type of your element. It is this type which implements your interface, so it's the right place to put the customization/implements.