0

I have a schema that defines a Type with optional boolean attributes. I would like to add a type that adds a restriction that sets the default value of the attributes to "true"

<xsd:complexType name="bob">
    <xsd:attribute name="isBob" type="xsd:boolean" use="optional" /> 
</xsd:complexType>

<xsd:complexType name="reallyBob">
    <xsd:complexContent>
        <xsd:restriction base="sa:bob">  
            <xsd:attribute name="isBob" type="xsd:boolean" default="true" use="optional" /> 
        </xsd:restriction>
    </xsd:complexContent>
</xsd:complexType>

however when we use JAXB to generate the Java classes for this class ReallyBob has no restriction applied.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "reallyBob")
public class ReallyBob
    extends Bob
{
}

Is there some way I can get the generated class ReallyBob to set the default value of the isBob Attribute?

I have seen similar questions about restrictions not being applied by JAXB, ie here and here Responses indicate turning on schema validation during Marshalling... I'm not sure how that would apply in this case, as its default values rather than value restrictions.

Perhaps there is another approach to this all together?

Community
  • 1
  • 1
Paul Henry
  • 355
  • 3
  • 9

1 Answers1

1

One option is to set the value after the unmarshalling has been completed.

This involves adding the following method to your object and set the object to the default value inside this method:

void afterUnmarshal(Unmarshaller u, Object parent) {
  this.isBob = true;
}

See related documentation here

kirsty
  • 267
  • 1
  • 2
  • 14
  • Thanks Kirsty, We can't use the "in class" callback as the classes are generated and any code chages would get discarded next time they are generated. However we could use an Instance of Unmarshaller.Listener to set the default values of our restricted (with default values) elements. That would work. However it does mean that we need to replicate the set of default values defined in the schema and in the Unmarshalling listener with all the chances for errors that entails.... but I haven't yet found any better way to achieve this. – Paul Henry Oct 19 '15 at 19:51
  • Ah my apologies, I didn't realize. Yes your solution would do the same as mine, just somewhere different! One final suggestion I have is that sometimes the JAXB annotations are not explicitly needed, have you checked that the default value is definitely not set? – kirsty Oct 20 '15 at 08:08