简体   繁体   中英

Applying a default value restriction in JAXB generated Java Classes

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM