blob: ad878b7d86308680ad98564f6fc93cfc21325259 [file] [log] [blame]
//
// Copyright (c) 2020 Contributors to the Eclipse Foundation
//
:sectnums:
= Jakarta XML Binding Specification, Version 2.1
Copyright (c) 2006, 2019 Oracle and/or its affiliates. All rights reserved.
Oracle and Java are registered trademarks of Oracle and/or its
affiliates. Other names may be trademarks of their respective owners.
== CHAPTER 1 -
[[a2]]Introduction
XML is, essentially, a platform-independent
means of structuring information. An XML document is a tree of
_elements_ . An element may have a set of _attributes_ , in the form of
key-value pairs, and may contain other elements, text, or a mixture
thereof. An element may refer to other elements via _identifier_
attributes or other types via _type_ attributes, thereby allowing
arbitrary graph structures to be represented.
An XML document need not follow any rules
beyond the well-formedness criteria laid out in the XML 1.0
specification. To exchange documents in a meaningful way, however,
requires that their structure and content be described and constrained
so that the various parties involved will interpret them correctly and
consistently. This can be accomplished through the use of a _schema_ . A
schema contains a set of rules that constrains the structure and content
of a document’s components, _i.e._ , its elements, attributes, and text.
A schema also describes, at least informally and often implicitly, the
intended conceptual meaning of a document’s components. A schema is, in
other words, a specification of the syntax and semantics of a
(potentially infinite) set of XML documents. A document is said to be
_valid_ with respect to a schema if, and only if, it satisfies the
constraints specified in the schema.
In what language is a schema defined? The XML
specification itself describes a sublanguage for writing _document-type
definitions_ , or DTDs. As schemas go, however, DTDs are fairly weak.
They support the definition of simple constraints on structure and
content, but provide no real facility for expressing datatypes or
complex structural relationships. They have also prompted the creation
of more sophisticated schema languages such as XDR, SOX, RELAX, TREX,
and, most significantly, the XML Schema language defined by the World
Wide Web Consortium. The XML Schema language has gained widespread
acceptance. It is the schema language of choice for many of the XML
related specifications authored by industry standard working groups.
Therefore, the design center for this specification is W3C XML Schema
language.
=== Data binding
Any nontrivial application of XML will, then,
be based upon one or more schemas and will involve one or more programs
that create, consume, and manipulate documents whose syntax and
semantics are governed by those schemas. While it is certainly possible
to write such programs using the low-level SAX parser API or the
somewhat higher-level DOM parse-tree API, doing so is not easy. The
resulting code is also difficult to maintain as the schemas evolve.
While useful to some, many applications access and manipulate XML
content within a document; its document structure is less relevant.
It would be much easier to write XML-enabled
programs if we could simply map the components of an XML document to
in-memory objects that represent, in an obvious and useful way, the
document’s intended meaning according to its schema. Of what classes
should these objects be instances? In some cases there will be an
obvious mapping from schema components to existing classes, especially
for common types such as _String_ , _Date_ , _Vector_ , and so forth. In
general, however, classes specific to the schema being used will be
required.
Classes specific to a schema may be derived or
may already exist. In some application scenarios e.g. web services, a
data model composed using user authored classes may already exist. A
schema is derived from existing classes. In-memory objects are instances
of existing classes. In other application scenarios, a data model is
composed by authoring a schema. In such cases, rather than burden
developers with having to write classes specific to schema, we can
generate the classes directly from the schema. In all application
scenarios, we create a Java object-level _binding_ of the schema.
But even applications manipulating documents
at conceptual object level, may desire to access or manipulate
structural information in a document, e.g. element names. Therefore, the
ability for an application to relate between the XML document
representation and the Java object-level binding enables the use of XML
operations over the XML document representation, e.g. Xpath.to bind XML
content to an object model such as DOM is useful.
An _XML data-binding facility_ therefore
contains a _schema compiler and a schema generator._ A schema compiler
can consume a schema and generate schema derived classes specific to the
schema. A schema generator consumes a set of existing classes and
generates a schema.
A schema compiler binds components of a
_source schema_ to schema-derived Java value classes. Each value class
provides access to the content of the corresponding schema component via
a set of JavaBeans-style access ( _i.e._ , _get_ and _set_ ) methods.
_Binding_ declarations provides a capability to customize the binding
from schema components to Java representation.
A schema generator binds existing classes to
schema components. Each class containing Java Beans-style access (
_i.e._ , _get_ and _set_ ) methods is bound to a corresponding schema
component. Program annotations provide a capability to customize the
binding from existing classes to derived schema components. Access to
content is through in-memory representation of existing classes.
Such a facility also provides a _binding
framework_ , a runtime API that, in conjunction with the derived or
existing classes, supports three primary operations:
* The _unmarshalling_ of an XML document into
a tree of interrelated instances of both existing and schema-derived
classes,
* The _marshalling_ of such _content trees_
back into XML documents, and
* The _binding,_ maintained by a _binder,_
between an XML document representation and _content tree_ .
The unmarshalling process has the capability
to check incoming XML documents for validity with respect to the
schema. +
image:xmlb-2.png[image]
=== Binding XML to Java objects
To sum up: Schemas describe the structure and
meaning of an XML document, in much the same way that a class describes
an object in a program. To work with an XML document in a program we
would like to map its components directly to a set of objects that
reflect the document’s meaning according to its schema. We can achieve
this by compiling the schema into a set of derived content classes or by
compiling a set of existing classes into a schema and marshalling,
unmarshalling and validating XML documents that follow the schema. Data
binding thus allows XML-enabled programs to be written at the same
conceptual level as the documents they manipulate, rather than at the
more primitive level of parser events or parse trees.
Schema evolution in response to changing
application requirements, is inevitable. A document therefore might not
always necessarily follow the complete schema, rather a part of a
versioned schema. Dealing with schema evolution requires both a
versioning strategy as well as more flexible marshalling, unmarshalling
and validation operations.
XML applications, such as workflow
applications, consist of distributed, cooperative components
interoperating using XML documents for data exchange. Each distributed
component may need to access and update only a part of the XML document
relevant to itself, while retaining the fidelity of the rest of the XML
document. This is also more robust in the face of schema evolution,
since the changes in schema may not impact the part of the document
relevant to the application. The _binder_ enables _partial binding_ of
the relevant parts of the XML document to a content tree and
_marshalling_ updates __ back to the original XML document.
=== [[a23]]Goals
The JAXB architecture is designed with the
goals outlined here in mind.
. [[a25]]Full W3C XML Schema
support
Support for XML Schema features not required
to be supported in JAXB 1.0 has been added in this version.
. [[a27]]Binding existing Java
classes to generated XML schema
This addresses application scenarios where
design begins with Java classes rather than an XML schema. One such
example is an application that exports itself as a web service that
communicates using SOAP and XML as a transport mechanism. The
marshalling of Java object graph is according to program annotations,
either explicit or defaulted, on the existing Java classes.
. Meet data binding
requirements for The Java API for XML Web Services(JAX-WS) 2.0
JAX-WS 2.0 will use the XML data binding
facility defined by JAXB 2.0. Hence, JAXB 2.0 will meet all data binding
requirements of JAX-WS 2.0.
. Ease of Development: Leverage J2SE 5.0
Language Extensions
For ease of development, J2SE 5.0 introduces
additional language language extensions.The language extensions include
generics (JSR 14), typesafe enums (JSR201), annotations (JSR 175). Use
of the language extensions in binding of XML schema components to Java
representation will result in a better and simpler binding, thus making
the application development easier.
. _Container Managed Environments_
A container managed environment separates
development from the deployment phases. This enables choice of
generation of artifacts such as derived classes or derived schema at
either development or deployment time.
Any requirements related to the deployment of
components using JAXB in a container managed environment will be
addressed.
. _Schema evolution_
Schema evolution is a complex and difficult
area; it is also an important area. It is particularly important in data
centric applications such as Web services, where distributed
applications interact using XML as a data interchange format but are
designed with different versions of the schema. It is also important in
document centric applications where schemas are designed for
extensibility. Strategies to address both application scenarios will be
investigated and support added accordingly.
. Application specific
behavior
There should be a way to associate application
specific behavior with schema derived code in a portable manner.
. _Partial mapping of XML document relevant
to application_
In some application scenarios, only a subset
of the data within a XML document may be relevant to the application.
. _Integration with other Java technologies_
Integration or relationship with the following
Java technologies will be clarified.
. Streaming API For XML (JSR 173) (StAX)
. Relationship to XML related specifications
XML related specifications will be surveyed to
determine their relationship to JAXB.
. Portability of JAXB mapped classes
An architecture that provides for a fully
portable JAXB 2.0 applications written to the J2SE platform will be
defined. JAXB 2.0 is targeted for inclusion in a future version of J2SE.
Application portability is a key requirement for inclusion in J2SE.
JAXB annotated classes must be source level
and binary compatible with any other JAXB 2.0 binding framework
implementation. As in JAXB 1.0, schema-derived interfaces/implementation
classes are only required to be source code compatible with other JAXB
implementations of the same version.
. _Preserving equivalence - Round tripping
(Java to XML to Java)_
Transforming a Java content tree to XML
content and back to Java content again should result in an equivalent
Java content tree before and after the transformation.
. _Preserving equivalence - Round tripping
(XML to Java to XML)_
While JAXB 1.0 specification did not require
the preservation of the XML information set when round tripping from XML
document to Java representation and back to XML document again, it did
not forbid the preservation either. The same applies to this version of
the specification.
. Unmarshalling invalid XML content
Unmarshalling of invalid content was out of
scope for JAXB 1.0. Simple binding rules and unmarshalling mechanisms
that specify the handling of invalid content will be defined.
. _Ease of Use - Manipulation of XML
documents in Java_
Lower the barrier to entry to manipulating XML
documents within Java programs. Programmers should be able to access and
modify XML documents via a Java binding of the data, not via SAX or DOM.
It should be possible for a developer who knows little about XML to
compile a simple schema and immediately start making use of the classes
that are produced. +
+
Rather than not supporting XML Schema extensibility concepts that can
not be statically bound, such as unconstrained wildcard content, these
concepts should be exposed directly as DOM or some other XML infoset
preserving representation since there is no other satisfactory static
Java binding representation for them.
. Customization
Applications sometimes require customization
to meet their data binding requirements. Customization support will
include:
* XML to Java:
A standard way to customize the binding of
existing XML schema components to Java representation will be provided.
JAXB 1.0 provided customization mechanisms for the subset of XML Schema
components supported in JAXB 1.0. Customization support will be extended
to additional XML Schema features to be supported in this version of the
specification link:jaxb.html#a25[See Full W3C XML Schema
support].
* Java to XML:
A standard way to customize the binding of
existing Java classes to XML schema will be added,
link:jaxb.html#a27[See Binding existing Java classes to
generated XML schema].
. Schema derived classes should be natural
Insofar as possible, derived classes should
observe standard Java API design guidelines and naming conventions. If
new conventions are required then they should mesh well with existing
conventions. A developer should not be astonished when trying to use a
derived class.
. Schema derived classes should match
conceptual level of source schema
It should be straightforward to examine any
content-bearing component of the source schema and identify the
corresponding Java language construct in the derived classes.
=== Non-Goals
* Support for Java versions prior to J2SE 5.0
JAXB 2.0 relies on many of the Java language
features added in J2SE 5.0. It is not a goal to support JAXB 2.0 on Java
versions prior to J2SE 5.0.
* _Explicit support for specifying the
binding of DTD to a Java representation_ .
While it was desired to explicitly support
binding DTD to a Java representation, it became impractical to describe
both XML Schema binding and DTD binding. The existence of several
conversion tools that automate the conversion of a DTD to XML Schema
allows DTD users to be able to take advantage of JAXB technology by
converting their existing DTDs to XML Schema.
* XML Schema Extensions
XML Schema specification allows the annotation
of schemas and schema components with appinfo elements. JAXB 1.0
specifies the use of appinfo elements to customize the generated code.
For this version of the specification, use of appinfo elements for
customization of generated code continues to be in scope. However, use
of appinfo element to introduce validation constraints beyond those
already described in XML Schema 1.0 specification is out of scope.
* Support for SOAP Encoding
SOAP Encoding is out of scope. Use of the SOAP
encoding is essentially deprecated in the web services community, e.g.
the WS-I Basic Profile[WSIBP] excludes SOAP encoding.
* Support for validation on demand by schema
derived classes
While working with a content tree
corresponding to an XML document it is often necessary to validate the
tree against the constraints in the source schema. JAXB 1.0 made it
possible to do this at any time, without the user having to first
marshal the tree into XML. However it is a non goal in JAXB 2.0, which
leverages the JAXP 1.3 validation API.
* _Object graph traversal_
Portable mechanisms to traverse a graph of
JavaBean objects will not be addressed in JAXB 2.0.
* _Mapping any existing Java classes to any
existing XML schema_
The JAXB annotation mechanism is not
sophisticated enough to enable mapping an arbitrary class to all XML
schema concepts.
=== Conventions
Within normative prose in this specification,
the words _should_ and _must_ are defined as follows:
* _should +
_ Conforming implementations are permitted to but need not behave as
described.
* _must +
_ Conforming implementations are required to behave as described;
otherwise they are in error.
Throughout the document, the XML namespace
prefix _xs:_ and _xsd:_ refers to schema components in W3C XML Schema
namespace as specified in [XSD Part 1] and [XSD Part 2]. The XML
namespace prefix _xsi:_ refers to the XML instance namespace defined in
[XSD Part 1]. Additionally, the XML namespace prefix _jaxb_ : refers to
the JAXB namespace, _http://java.sun.com/xml/ns/jaxb_ . The XML
namespace prefix _ref:_ refers to the namespace
_http://ws-i.org/profiles/basic/1.1/xsd_ as defined in [WSIBP] and
[WSIAP].
All examples in the specification are for
illustrative purposes to assist in understanding concepts and are
non-normative. If an example conflicts with the normative prose, the
normative prose always takes precedence over the example.
=== Expert Group Members
The following people have contributed to this
specification.
[width="100%",cols="50%,50%",]
|===
|Chavdar Baikov |SAP
AG
|David Bau |
|Arnaud Blandin |
|Stephen Brodsky
|IBM
|Russell Butek |IBM
|Jongjin Choi |TMAX
|Glen Daniels |Sonic
Software
|Blaise Doughan
|Oracle
|Christopher Fry
|BEA Systems
|Stanley Guan
|Oracle
|Mette Hedin |
|Kohsuke Kawaguchi
|Sun Microsystems, Inc.
|Sravan Kumar
|Pramati Technologies
|Changshin Lee |Tmax
Soft, Inc.
|Anjana Manian
|Oracle
|Ed Merks |IBM
|Steve Perry
|Fidelity Information Services
|Radu Preotiuc-Pietro
|BEA
|Srividya Rajagopalan
|Nokia Corporation
|Yann Raoul |
|Bjarne Rasmussen
|Novell, Inc.
|Adinarayana Sakala
|IONA Technologies PLC
|Dennis M. Sosnoski
|
|Keith Visco |
|Stefan Wachter |
|Umit Yalcinalp |
|Scott Ziegler |BEA
Systems
|Zulfi Umrani
|Novell, Inc.
|===
=== Acknowledgements
This document is a derivative work of concepts
and an initial draft initially led by Mark Reinhold of Sun Microsystems.
Our thanks to all who were involved in pioneering that initial effort.
The feedback from the Java User community on the initial JAXB technology
prototype greatly assisted in identifying requirements and directions.
The data binding experiences of the expert
group members have been instrumental in identifying the proper blend of
the countless data binding techniques that we have considered in the
course of writing this specification. We thank them for their
contributions and their review feedback.
Kohsuke Kawaguchi and Ryan Shoemaker have
directly contributed content to the specification and wrote the
companion javadoc. The following JAXB technology team members have been
invaluable in keeping the specification effort on the right track: Tom
Amiro, Leonid Arbouzov, Evgueni Astigueevitch, Jennifer Ball, Carla
Carlson, Patrick Curran, Scott Fordin, Omar Fung, Peter Kacandes, Dmitry
Khukhro, Tom Kincaid, K. Ari Krupnikov, Ramesh Mandava, Bhakti Mehta, Ed
Mooney, Ilya Neverov, Oleg Oleinik, Brian Ogata, Vivek Pandey, Cecilia
Peltier, Evgueni Rouban and Leslie Schwenk. The following people, all
from Sun Microsystems, have provided valuable input to this effort:
Roberto Chinnici, Chris Ferris, Mark Hapner, Eve Maler, Farrukh Najmi,
Eduardo Pelegri-llopart, Bill Shannon and Rahul Sharma.
The JAXB TCK software team would like to
acknowledge that the NIST XML Schema test suite [NIST] has greatly
assisted the conformance testing of this specification.
=== Acknowledgements for JAXB 2.0
Version 2.0 of this specification was created
under the Java Community Process as JSR-222. This specification is
shaped by valuable input from expert group members, people with Sun, and
Java User community feedback based on their experience with JAXB 1.0.
The data binding experience of the expert
group has been very instrumental in identifying usage scenarios
(including those from web services),design and evaluation of different
databinding techniques. We thank them for their contributions and review
feedback.
The following people, all from Sun
Microsystems, have provided valuable input. The experiences of the
reference implementation team, led by Kohsuke Kawaguchi, has been
influential in identifying data binding solutions. Kohsuke Kawaguchi and
Ryan Shoemaker have directly contributed content to the companion
javadoc.Addtional feedback was provided by the following JAXB technology
team members: Bhakti Mehta, Ed Mooney, Ryan Shoemaker, Karthikeyan
Krishnamurthy, Tom Amiro, Leonid Arbouzov, Leonid Kuskov, Dmitry
Fazunenko, Dmitry Lepekhin, Alexey Vishentsev, Omar Fung, and Anita
Jindal. Valuable input was provided by the following people from Sun:
Eduardo Pelegri-Llopart, Graham Hamilton, Mark Hapner, Bill Shannon.
The JAXB TCK software team would like to
acknowledge that the NIST XML Schema test suite [NIST] has greatly
assisted the conformance testing of this specification.
== CHAPTER 2 -
[[a151]]Requirements
This chapter specifies the scope and
requirements for this version of the specification.
=== XML Schema to Java
=== W3C XML Schema support
The mapping of the following XML Schema
components must be specified.
* type substitution ( _@xsi:type_ )
* element substitution group ( _<xs:element
@substitutionGroup_ >)
* wildcard support( _xs:any_ and
_xs:anyAttribute_ )
* identity constraints ( _xs:key_ ,
_xs:keyref_ and _xs:unique_ )
* redefinition of declaration ( _xs:redefine_
)
* NOTATION
For binding builtin XML Schema datatypes which
do not map naturally to Java datatypes, Java datatypes specified by JAXP
1.3 (JSR 206) must be used.
=== Default Bindings
There must be a detailed, unambiguous
description of the default mapping of schema components to Java
representations in order to satisfy the portability goal.
=== [[a165]]Customized Binding Schema
A binding schema language and its formats must
be specified. There must be a means to describe the binding without
requiring modification to the original schema. Additionally, the same
XML Schema language must be used for the two different mechanisms for
expressing a binding declaration.
=== Overriding default binding behavior
Given the diverse styles that can be used to
design a schema, it is daunting to identify a single ideal default
binding solution. For situations where several equally good binding
alternatives exist, the specification will describe the alternatives and
select one to be the default (see link:jaxb.html#a165[See
Customized Binding Schema]).
The binding schema must provide a means to
specify an alternative binding for the scope of an entire schema. This
mechanism ensures that if the default binding is not sufficient, it can
easily be overridden in a portable manner.
=== JAX-WS 2.0
=== Backward Compatibility
Mapping of XML Schema to schema derived Java
classes as specified in versions of JAX-RPC 1.x either by default or by
customization is out of scope.
=== Binding XML Schema to schema derived classes
A binding of XML Schema constructs to schema
derived classes must be specified. JAXB 1.0 specified the binding of XML
Schema constructs to schema derived interfaces. However, JAX-RPC 1.x
specified the binding of XML Schema constructs to schema derived
classes, not interfaces. To provide continued support for JAX-RPC 1.x
programming model, a customization to enable the binding of XML Schema
constructs to schema derived classes will be added.
=== Accessing MIME content stored as an attachment
The W3C XMLP MTOM/XOP document and WS-I AP
1.0[WSIAP] both provide mechanisms for embedding references to SOAP
attachments in SOAP messages. It is desirable to bind these to suitable
Java types (e.g. Image or DataHandler) rather than just provide URI
refs.
=== Serializable
A customization must be specified to enable
schema derived classes to implement the _java.io.Serializable_
interface. This capability enables the schema derived instance to be
passed as EJB method parameter and to any other API that requires
Serializable instances.
=== [[a179]]Disabling Databinding
A customization to disable databinding must be
specified. When databinding is disabled, an XML Schema component is
bound to an XML fragment representation rather than a strongly typed
datatype determined by mapping rules. Binding to XML fragment allows the
use of alternative binding technologies for example to perform XML
operations.
=== Java to XML Schema
=== [[a182]]Default Mapping
A default mapping Java constructs to XML
Schema must be specified. The default mapping may be overridden by
customizations described in link:jaxb.html#a184[See Customized
Mapping]”.
=== [[a184]]Customized Mapping
A customization mechanism to override default
mapping of Java constructs to XML Schema constructs must be specified.
Since XML Schema provides a much richer feature set than Java language
for defining data models, the scope of customizations will be restricted
to enable mapping to commonly used XML Schema constructs.
Support for the following mechanism must be
specified:
* customization mechanism using the JSR175
program annotation facility.
=== JAX-WS 2.0
=== WSDL <types>
The WSDL <types> is generated using Java
constructs to XML Schema mapping. The latter should therefore define
customizations that enable mapping to XML Schema constructs commonly
used in web services, subject to the requirements in
link:jaxb.html#a184[See Customized Mapping]” and
link:jaxb.html#a182[See Default Mapping]”.
=== Backward Compatibility
Mapping of existing Java constructs to XML
Schema constructs as specified in JAX-RPC versions 1.x, either by
default or through customization, is out of scope.
=== Binding Framework
=== Disabling schema validation
The specification will provide an ability _to
disable schema validation for unmarshal and marshal operations._
There exist a significant number of scenarios
that do not require validation and/or can not afford the overhead of
schema validation. An application must be allowed to disable schema
validation checking during unmarshal and marshal operations. The goal of
this requirement is to provide the same flexibility and functionality
that a SAX or DOM parser allows for.
== CHAPTER 3 -
Architecture
=== Introduction
This chapter describes the architectural
components, comprising the XML-databinding facility, that realize the
goals outlined in link:jaxb.html#a23[See Goals]”. The scope of
this version of specification covers many additional goals beyond those
in JAXB 1.0. As a result, JAXB 1.0 architecture has been revised
significantly.
=== Overview
The XML data-binding facility consists of the
following architectural components:
* schema compiler: A schema compiler binds a
source schema to a set of schema derived program elements. The binding
is described by an XML-based language, binding language.
* schema generator: A schema generator maps a
set of existing program elements to a derived schema. The mapping is
described by program annotations.
* binding runtime framework that provides two
primary operations for accessing, manipulating and validating XML
content using either schema derived or existing program elements:
* _Unmarshalling_ is the process of reading
an XML document and constructing a tree of content objects. Each content
object is an instance of either a schema derived or an existing program
element mapped by the schema generator and corresponds to an instance in
the XML document. Thus, the content tree reflects the document’s
content. Validation can optionally be enabled as part of the
unmarshalling process. _Validation_ is the process of verifying that an
xml document meets all the constraints expressed in the schema.
* _Marshalling_ is the inverse of
unmarshalling, i.e., it is the process of traversing a content tree and
writing an XML document that reflects the tree’s content. Validation can
optionally be enabled as part of the marshalling process.
As used in this specification, the term
_schema_ includes the W3C XML Schema as defined in the XML Schema 1.0
Recommendation[XSD Part 1][XSD Part 2]. link:jaxb.html#a210[See
Non-Normative JAXB 2.0 Architecture diagram] illustrates relationships
between concepts introduced in this section.
image:xmlb-3.png[image]
=== [[a210]]Non-Normative JAXB 2.0 Architecture diagram
JAXB-annotated classes are common to both
binding schemes. They are either generated by a schema compiler or the
result of a programmer adding JAXB annotations to existing Java classes.
The universal unmarshal/marshal process is driven by the JAXB
annotations on the portable JAXB-annotated classes.
Note that the binding declarations object in
the above diagram is logical. Binding declarations can either be inlined
within the schema or they can appear in an external binding file that is
associated with the source schema.
=== JAXB 1.0 style binding of schema to interface/implementation classes.
image:xmlb-4.png[image]
Note that the application accesses only the
schema-derived interfaces, factory methods and _jakarta.xml.bind_ APIs
directly. This convention is necessary to enable switching between JAXB
implementations.
=== Java Representation
The content tree contains instances of bound
types, types that bind and provide access to XML content. Each bound
type corresponds to one or more schema components. As much as possible,
for type safety and ease of use, a bound type that constrains the values
to match the schema constraints of the schema components. The different
bound types, which may be either schema derived or authored by a user,
are described below.
Value Class A coarse grained schema
component, such as a complex type definition, is bound to a Value class.
The Java class hierarchy is used to preserve XML Schema’s “derived by
extension” type definition hierarchy. JAXB-annotated classes are
portable and in comparison to schema derived interfaces/implementation
classes, result in a smaller number of classes.
Property A fine-grained schema component,
such as an attribute declaration or an element declaration with a simple
type, is bound directly to a _property_ or a field within a value class.
A property is _realized_ in a value class by
a set of JavaBeans-style _access methods_ . These methods include the
usual _get_ and _set_ methods for retrieving and modifying a property’s
value; they also provide for the deletion and, if appropriate, the
re-initialization of a property’s value.
Properties are also used for references from
one content instance to another. If an instance of a schema component
_X_ can occur within, or be referenced from, an instance of some other
component _Y_ then the content class derived from _Y_ will define a
property that can contain instances of _X_ .
Binding a fine-grained schema component to a
field is useful when a bound type does not follow the JavaBeans
patterns. It makes it possible to map such types to a schema without the
need to refactor them.
Interface JAXB 1.0 bound schema components
(XML content) to schema derived content interfaces and implementation
classes. The interface/implementation classes tightly couple the schema
derived implementation classes to the JAXB implementation runtime
framework and are thus not portable. The binding of schema components to
schema derived interfaces continues to be supported in JAXB 2.0.
*
Enum type J2SE 5.0 platform introduced
linguistic support for type safe enumeration types. Enum type are used
to represent values of schema types with enumeration values.
Collection type Collections are used to
represent content models. Where possible, for type safety, parametric
lists are used for homogeneous collections. For e.g. a repeating element
in content model is bound to a parametric list.
DOM node In some cases, binding XML content
to a DOM or DOM like representation rather than a collection of types is
more natural to a programmer. One example is an open content model that
allows elements whose types are not statically constrained by the
schema.
Content tree can be created by unmarshalling
of an XML document or by programmatic construction. Each bound type in
the content tree is created as follows:
* schema derived implementation classes that
implement schema derived interfaces can be created using factory methods
generated by the schema compiler.
* schema derived value classes can be created
using a constructor or a factory method generated by the schema
compiler.
* existing types, authored by users, are
required to provide a no arg constructor. The no arg constructor is used
by an unmarshaller during unmarshalling to create an instance of the
type.
=== Binding Declarations
A particular binding of a given source schema
is defined by a set of _binding declarations_ . Binding declarations are
written in a _binding language_ , which is itself an application of XML.
A binding declaration can occur within the annotation _appinfo_ of each
XML Schema component. Alternatively, binding declarations can occur in
an auxiliary file. Each binding declaration within the auxiliary file is
associated to a schema component in the source schema. It was necessary
to support binding declarations external to the source schema in order
to allow for customization of an XML Schemas that one prefers not to
modify. The schema compiler hence actually requires two inputs, a source
schema and a set of binding declarations.
Binding declarations enable one to override
default binding rules, thereby allowing for user customization of the
schema-derived value class. Additionally, binding declarations allow for
further refinements to be introduced into the binding to Java
representation that could not be derived from the schema alone.
The binding declarations need not define
every last detail of a binding. The schema compiler assumes _default
binding declarations_ for those components of the source schema that are
not mentioned explicitly by binding declarations. Default declarations
both reduce the verbosity of the customization and make it more robust
to the evolution of the source schema. The defaulting rules are
sufficiently powerful that in many cases a usable binding can be
produced with no binding declarations at all. By defining a standardized
format for the binding declarations, it is envisioned that tools will be
built to greatly aid the process of customizing the binding from schema
components to a Java representation.
=== Mapping Annotations
A mapping annotation defines the mapping of a
program element to one or more schema components. A mapping annotation
typically contains one or more annotation members to allow customized
binding. An annotation member can be required or optional. A mapping
annotation can be collocated with the program element in the source. The
schema generator hence actually requires both inputs: a set of classes
and a set of mapping annotations.
Defaults make it easy to use the mapping
annotations. In the absence of a mapping annotation on a program
element, the schema generator assumes, when required by a mapping rule,
a default mapping annotation. This, together with an appropriate choice
of default values for optional annotation members makes it possible to
produce in many cases a usable mapping with minimal mapping annotations.
Thus mapping annotations provide a powerful yet easy to use
customization mechanism
=== Annotations
Many of the architectural components are
driven by program annotations defined by this specification, mapping
annotations.
Java to Schema Mapping Mapping annotations
provide meta data that describe or customize the mapping of existing
classes to a derived schema.
Portable Value Classes Mapping annotations
provide information for unmarshalling and marshalling of an XML instance
into a content tree representing the XML content without the need for a
schema at run time. Thus schema derived code annotated with mapping
annotations are portable i.e. they are capable of being marshalled and
unmarshalled by a universal marshaller and unmarshaller written by a
JAXB vendor implementation.
Adding application specific behavior and data
Applications can choose to add either behavior or data to schema derived
code. link:jaxb.html#a1459[See Modifying Schema-Derived Code]”
specifies how the mapping annotation, _@javax.annotation.Generated_ ,
should be used by a developer to denote developer added/modified code
from schema-derived code. This information can be utilized by tools to
preserve application specific code across regenerations of schema
derived code.
=== Binding Framework
The binding framework has been revised
significantly since JAXB 1.0. Significant changes include:
* support for unmarshalling of invalid XML
content.
* deprecation of on-demand validation.
* unmarshal/marshal time validation deferring
to JAXP 1.3 validation.
=== Unmarshalling
=== Invalid XML Content
Rationale: Invalid XML content can arise for
many reasons:
* When the cost of validation needs to be
avoided.
* When the schema for the XML has evolved.
* When the XML is from a non-schema-aware
processor.
* When the schema is not authoritative.
Support for invalid XML content required
changes to JAXB 1.0 schema to java binding rules as well as the
introduction of a flexible unmarshalling mode. These changes are
described in link:jaxb.html#a379[See Unmarshalling Modes]”.
=== [[a256]]Validation
The constraints expressed in a schema fall
into three general categories:
* A _type_ constraint imposes requirements
upon the values that may be provided by constraint facets in simple type
definitions.
* A _local structural_ constraint imposes
requirements upon every instance of a given element type, e.g., that
required attributes are given values and that a complex element’s
content matches its content specification.
* A _global structural_ constraint imposes
requirements upon an entire document, e.g., that _ID_ values are unique
and that for every _IDREF_ attribute value there exists an element with
the corresponding _ID_ attribute value.
A _document_ is valid if, and only if, all of
the constraints expressed in its schema are satisfied. The manner in
which constraints are enforced in a set of derived classes has a
significant impact upon the usability of those classes. All constraints
could, in principle, be checked only during unmarshalling. This approach
would, however, yield classes that violate the _fail-fast_ principle of
API design: errors should, if feasible, be reported as soon as they are
detected. In the context of schema-derived classes, this principle
ensures that violations of schema constraints are signalled when they
occur rather than later on when they may be more difficult to diagnose.
With this principle in mind we see that schema
constraints can, in general, be enforced in three ways:
* _Static_ enforcement leverages the type
system of the Java programming language to ensure that a schema
constraint is checked at application’s compilation time. Type
constraints are often good candidates for static enforcement. If an
attribute is constrained by a schema to have a boolean value, e.g., then
the access methods for that attribute’s property can simply accept and
return values of type _boolean_ .
* _Simple dynamic_ enforcement performs a
trivial run-time check and throws an appropriate exception upon failure.
Type constraints that do not easily map directly to Java classes or
primitive types are best enforced in this way. If an attribute is
constrained to have an integer value between zero and 100, e.g., then
the corresponding property’s access methods can accept and return _int_
values and its mutation method can throw a run-time exception if its
argument is out of range.
* _Complex dynamic_ enforcement performs a
potentially costly run-time check, usually involving more than one
content object, and throwing an appropriate exception upon failure.
Local structural constraints are usually enforced in this way: the
structure of a complex element’s content, e.g., can in general only be
checked by examining the types of its children and ensuring that they
match the schema’s content model for that element. Global structural
constraints must be enforced in this way: the uniqueness of _ID_ values,
e.g., can only be checked by examining the entire content tree.
It is straightforward to implement both static
and simple dynamic checks so as to satisfy the fail-fast principle.
Constraints that require complex dynamic checks could, in theory, also
be implemented so as to fail as soon as possible. The resulting classes
would be rather clumsy to use, however, because it is often convenient
to violate structural constraints on a temporary basis while
constructing or manipulating a content tree.
Consider, e.g., a complex type definition
whose content specification is very complex. Suppose that an instance of
the corresponding value class is to be modified, and that the only way
to achieve the desired result involves a sequence of changes during
which the content specification would be violated. If the content
instance were to check continuously that its content is valid, then the
only way to modify the content would be to copy it, modify the copy, and
then install the new copy in place of the old content. It would be much
more convenient to be able to modify the content in place.
A similar analysis applies to most other sorts
of structural constraints, and especially to global structural
constraints. Schema-derived classes have the ability to enable or
disable a mode that verifies type constraints. JAXB mapped classes can
optionally be validated at unmarshal and marshal time.
=== Validation Re architecture
The detection of complex schema constraint
violations has been redesigned to have a JAXB 2.0 implementation to
delegate to the validation API in JAXP 1.3. JAXP 1.3 defines a standard
validation API ( _javax.xml.validation_ package) for validating XML
content against constraints within a schema. Furthermore, JAXP 1.3 has
been incorporated into J2SE 5.0 platform. Any JAXB 2.0 implementation
that takes advantage of the validation API will result in a smaller
footprint.
=== Unmarshal validation
When the unmarshalling process incorporates
validation and it successfully completes without any validation errors,
both the input document and the resulting content tree are guaranteed to
be valid.
However, always requiring validation during
unmarshalling proves to be too rigid and restrictive a requirement.
Since existing XML parsers allow schema validation to be disabled, there
exist a significant number of XML processing uses that disable schema
validation to improve processing speed and/or to be able to process
documents containing invalid or incomplete content. To enable the JAXB
architecture to be used in these processing scenarios, the binding
framework makes validation optional.
=== Marshal Validation
Validation may also be optionally performed
at marshal time. This is new for JAXB 2.0. Validation of object graph
while marshalling is useful in web services where the marshalled output
must conform to schema constraints specified in a WSDL document. This
could provide a valuable debugging aid for dealing with any
interoperability problems
=== Handling Validation Failures
While it would be possible to notify a JAXB
application that a validation error has occurred by throwing a
_JAXBException_ when the error is detected, this means of communicating
a validation error results in only one failure at a time being handled.
Potentially, the validation operation would have to be called as many
times as there are validation errors. Both in terms of validation
processing and for the application’s benefit, it is better to detect as
many errors and warnings as possible during a single validation pass. To
allow for multiple validation errors to be processed in one pass, each
validation error is mapped to a validation error event. A validation
error event relates the validation error or warning encountered to the
location of the text or object(s) involved with the error. The stream of
potential validation error events can be communicated to the application
either through a registered validation event handler at the time the
validation error is encountered, or via a collection of validation
failure events that the application can request after the operation has
completed.
Unmarshalling and marshalling are the two
operations that can result in multiple validation failures. The same
mechanism is used to handle both failure scenarios. See
link:jaxb.html#a326[See General Validation Processing] for
further details.
=== An example
Throughout this specification we will refer
and build upon the familiar schema from [XSD Part 0], which describes a
purchase order, as a running example to illustrate various binding
concepts as they are defined. Note that all schema name attributes with
values in _this font_ are bound by JAXB technology to either a Java
interface or JavaBean-like property. Please note that the derived Java
code in the example only approximates the default binding of the
schema-to-Java representation.
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"> +
<xsd:element name= _"purchaseOrder"_ type= _"PurchaseOrderType"_ /> +
<xsd:element name= _"comment"_ type=" _xsd:string"_ /> +
<xsd:complexType name= _"PurchaseOrderType"_ > +
<xsd:sequence> +
<xsd:element name= _"shipTo"_ type="USAddress"/> +
<xsd:element name= _"billTo"_ type="USAddress"/> +
<xsd:element ref= _"comment"_ minOccurs="0"/> +
<xsd:element name= _"items"_ type="Items"/> +
</xsd:sequence> +
<xsd:attribute name= _"orderDate"_ type="xsd:date"/> +
</xsd:complexType> +
+
<xsd:complexType name= _"USAddress"_ > +
<xsd:sequence> +
<xsd:element name= _"name"_ type="xsd:string"/> +
<xsd:element name= _"street"_ type="xsd:string"/> +
<xsd:element name= _"city"_ type="xsd:string"/> +
<xsd:element name= _"state"_ __ type="xsd:string"/> +
<xsd:element name= _"zip"_ type="xsd:decimal"/> +
</xsd:sequence> +
<xsd:attribute name= _"country"_ type="xsd:NMTOKEN" fixed="US"/> +
</xsd:complexType> +
+
<xsd:complexType name= _"Items"_ > +
<xsd:sequence> +
<xsd:element name= _"item"_ minOccurs="1" maxOccurs="unbounded"> +
<xsd:complexType>
<xsd:sequence> +
<xsd:element name= _"productName"_ type="xsd:string"/> +
<xsd:element name= _"quantity"_ > +
<xsd:simpleType> +
<xsd:restriction base="xsd:positiveInteger"> +
<xsd:maxExclusive value="100"/> +
</xsd:restriction> +
</xsd:simpleType> +
</xsd:element> +
<xsd:element name= _"USPrice"_ type="xsd:decimal"/> +
<xsd:element ref= _"comment"_ minOccurs="0"/> +
<xsd:element name= _"shipDate"_ type="xsd:date" minOccurs="0"/> +
</xsd:sequence> +
<xsd:attribute name= _"partNum"_ type="SKU" use="required"/> +
</xsd:complexType> +
</xsd:element> +
</xsd:sequence> +
</xsd:complexType>
+
<!-- Stock Keeping Unit, a code for identifying products --> +
<xsd:simpleType name= _"SKU"_ > +
<xsd:restriction base="xsd:string"> +
<xsd:pattern value="\d\{3}-[A-Z]\{2}"/> +
</xsd:restriction> +
</xsd:simpleType> +
</xsd:schema>
Binding of purchase order schema to a Java
representationlink:#a5352[1]:
import
javax.xml.datatype.XMLGregorianCalendar; import java.util.List; +
public class _PurchaseOrderType_ _\{ +
_ USAddress get _ShipTo_ ()\{...} void set _ShipTo_ (USAddress)\{...} +
USAddress get _BillTo_ ()\{...} void set _BillTo_ (USAddress)\{...} +
/** Optional to set Comment property. */ +
String get _Comment_ ()\{...} void set _Comment_ (String)\{...} +
Items get _Items_ ()\{...} void set _Items_ (Items)\{...} +
XMLGregorianCalendar get _OrderDate_ () void set _OrderDate_
(XMLGregorianCalendar) +
}; +
public class _USAddress \{ +
_ String get _Name_ ()\{...} void set _Name_ (String)\{...} +
String get _Street_ ()\{...} void set _Street_ (String) \{...} +
String get _City_ ()\{...} void set _City_ (String)\{...} +
String get _State_ ()\{...} void set _State_ (String)\{...} +
int get _Zip_ ()\{...} void set _Zip_ (int)\{...} +
static final String _COUNTRY_ =”USA”;link:#a5353[2] +
}; +
public class _Items_ \{ +
public class _ItemType_ \{ +
String get _ProductName_ _()\{...}_ void set _ProductName_
(String)\{...} +
/** Type constraint on Quantity setter value
0..99.link:#a5354[3]*/ +
int get _Quantity_ ()\{...} void set _Quantity_ (int)\{...} +
float get _USPrice_ ()\{...} void set _USPrice_ (float)\{...} +
/** Optional to set Comment property. */ +
String get _Comment_ ()\{...} void set _Comment_ (String)\{...} +
XMLGregorianCalendar get _ShipDate_ (); void set _ShipDate_
(XMLGregorianCalendar); +
/** Type constraint on PartNum setter value "\d\{3}-[A-Z]\{2}".2*/ +
String get _PartNum_ ()\{...} void set _PartNum_ (String)\{...} +
}; +
+
/** Local structural constraint 1 or more instances of _Items.ItemType_
.*/ +
List<Items.ItemType> get _Item_ ()\{...} +
} +
public class ObjectFactory \{ +
// type factories +
Object newInstance(Class javaInterface)\{...} +
PurchaseOrderType create _PurchaseOrderType_ ()\{...} +
USAddress create _USAddress_ ()\{...} +
Items create _Items_ ()\{...} +
Items.ItemType create _ItemsItemType_ ()\{...} +
// element factories +
JAXBElement<PurchaseOrderType> create _PurchaseOrder_
(PurchaseOrderType)\{...} +
JAXBElement<String> create _Comment_ (String value)\{...} +
}
The purchase order schema does not describe
any global structural constraints.
The coming chapters will identify how these
XML Schema concepts were bound to a Java representation. Just as in [XSD
Part 0], additions will be made to the schema example to illustrate the
binding concepts being discussed.
== CHAPTER 4 -
The Binding Framework
The _binding framework_ defines APIs to
access unmarshalling, validation and marshalling operations for
manipulating XML data and JAXB mapped objects. The framework is
presented here in overview; its full specification is available in the
javadoc for the package _jakarta.xml.bind_ .
The binding framework resides in two main
packages. The _jakarta.xml.bind_ package defines abstract classes and
interfaces that are used directly with content classes. The
_jakarta.xml.bindlink:#a5355[4]_ package defines the
_Unmarshaller, Marshaller_ and _Binder_ classes, which are auxiliary
objects for providing their respective operations.
The _JAXBContext_ class is the entry point
for a Java application into the JAXB framework. A _JAXBContext_ instance
manages the binding relationship between XML element names to Java value
class for a JAXB implementation to be used by the unmarshal, marshal and
binder operations. The _jakarta.xml.bind.helper_ package provides partial
default implementations for some of the _jakarta.xml.bind_ interfaces.
Implementations of JAXB technology can extend these classes and
implement the abstract methods. These APIs are not intended to be used
directly by applications using the JAXB architecture. A third package,
_jakarta.xml.bind.util_ , contains utility classes that may be used
directly by client applications.
The binding framework defines a hierarchy of
exception and validation event classes for use when
marshalling/unmarshalling errors occur, when constraints are violated,
and when other types of errors are detected.
=== Annotation-driven Binding Framework
The portability of JAXB annotated classes is
achieved via an annotation-driven architecture. The program annotations,
specified in Section 8, describe the mapping from the Java program
elements to XML Schema components. This information is used by the
binding framework to unmarshal and marshal to XML content into/from
JAXB-annotated classes. All JAXB schema binding compilers must be able
to generate portable schema-derived JAXB-annotated classes following the
constraints described in Section 6, link:jaxb.html#a694[See
Binding XML Schema to Java
Representations]link:jaxb.html#a694[See Binding XML Schema to
Java Representations]link:jaxb.html#a694[See Binding XML Schema
to Java Representations]”. All binding runtime frameworks are required
to be able to marshal and unmarshal portable JAXB-annotated classes
generated by other JAXB 2.0 schema binding compiler.
It is not possible to require portability of
the interface/implementation binding from JAXB 1.0. For backwards
compatibility with existing implementations, that binding remains a
tight coupling between the schema-derived implementation classes and the
JAXB implementation’s runtime framework. Users are required to
regenerate the schema-derived implementation classes when changing JAXB
implementations.
=== [[a298]]JAXBContext
The _JAXBContext_ class provides the client’s
entry point to the JAXB API. It provides an abstraction for managing the
XML/Java binding information necessary to implement the JAXB binding
framework operations: unmarshal and marshal.
The following summarizes the _JAXBContext_
class defined in package _jakarta.xml.bind_ .
public abstract class JAXBContext \{
static final String JAXB_CONTEXT_FACTORY;
static JAXBContext newInstance(String
contextPath);
static JAXBContext newInstance(String
contextPath, +
ClassLoader contextPathCL);
static JAXBContext newInstance(Class...
classesToBeBound); +
abstract Unmarshaller createUnmarshaller();
abstract Marshaller createMarshaller();
abstract JAXBIntrospector
createJAXBIntrospector(); +
<T> Binder<T> createBinder(Class<T> domType); +
Binder<org.w3c.dom.Node> createBinder(); +
void generateSchema(SchemaOutputResolver);
}
To avoid the overhead involved in creating a
JAXBContext instance, a JAXB application is encouraged to reuse a
JAXBContext instance. An implementation of abstract class JAXBContext is
required to be thread-safe, thus, multiple threads in an application can
share the same JAXBContext instance.
A client application configures a JAXBContext
using the _JAXBContext.newInstance(String contextPath)_ factory method.
JAXBContext jc =
JAXBContext.newInstance(
“com.acme.foo:com.acme.bar” );
The above example initializes a _JAXBContext_
with the schema-derived Java packages _com.acme.foo_ and _com.acme.bar_
. A _jaxb.index_ resource file, described in more detail in the javadoc,
list the non-schema-derived classes, namely the java to schema binding,
in a package to register with _JAXBContext_ . Additionally, in each
specified directory, if an optional resource filelink:#a5356[5]
containing package level mapping annotations exist, it is incorporated
into the JAXBContext representation.
An alternative mechanism that could be more
convenient when binding Java classes to Schema is to initialize
JAXBContext by passing JAXB-annotated class objects.
JAXBContext jc = +
JAXBContext.newInstance( POElement.class );
The classes specified as parameters to
_newInstance_ and all classes that are directly/indirectly referenced
statically from the specified classes are included into the returned
_JAXBContext_ instance. For each directory of all the classes imported
into JAXBContext, if an optional resource file2 containing package level
mapping annotations exists, it is incorporated into the JAXBContext
representation.
For example, given the following Java
classes:
@XmlRootElementlink:#a5357[6] class
Foo \{ Bar b;} +
@XmlType class Bar \{ FooBar fb;}
@XmlType class FooBar \{ int x; }
The invocation of
_JAXBContext.newInstance(Foo.class)_ registers Foo and the statically
referenced classes, _Bar_ and _FooBar_ .
Note that the jaxb.index resource file is not
necessary when an application uses
_JAXBContenxt.newInstances(Class...classesToBeBound)_ .
For either scenario, the values of these
parameters initialize the JAXBContext object so that it is capable of
managing the JAXB mapped classes.
See the javadoc for _JAXBContext_ for more
details on using this class.
*
=== [[a326]]General Validation Processing
Three identifiable forms of validation exist
within the JAXB architecture include:
* _Unmarshal-time validation_
This form of validation enables a client
application to be notified of validation errors and warnings detected
while unmarshalling XML data into a Java content tree and is completely
orthogonal to the other types of validation. See
jakarta.xml.bind.Unmarshaller javadoc for a description on how to enable
this feature.
* _On-demand validation_
This mode of validation is deprecated in JAXB
2.0. See link:jaxb.html#a5094[See On-demand Validation]” for the
JAXB 1.0 description of this functionality.
* _Fail-fast validation_
This form of validation enables a client
application to receive immediate feedback about a modification to the
Java content tree that violates a type constraint of a Java property. An
unchecked exception is thrown if the value provided to a set method is
invalid based on the constraint facets specified for the basetype of the
property. This style of validation is optional in this version of the
specification. Of the JAXB implementations that do support this type of
validation, it is customization-time decision to enable or disable
fail-fast validation when setting a property. __
Unmarshal-time uses an event-driven mechanism
to enable multiple validation errors and warnings to be processed during
a single operation invocation. If the validation or unmarshal operation
terminates with an exception upon encountering the first validation
warning or error, subsequent validation errors and warnings would not be
discovered until the first reported error is corrected. Thus, the
validation event notification mechanism provides the application a more
powerful means to evaluate validation warnings and errors as they occur
and gives the application the ability to determine when a validation
warning or error should abort the current operation (such as a value
outside of the legal value space). Thus, an application could allow
locally constrained validation problems to not terminate validation
processing.
If the client application does not set an
event handler on a _Unmarshaller_ or _Marshaller_ instance prior to
invoking the _unmarshal_ or _marshal_ operations, then a default event
handler will receive notification of any errors or fatal errors
encountered and stop processing the XML data. In other words, the
default event handler will fail on the first error that is encountered.
There are three ways to handle validation
events encountered during the unmarshal and marshal operations:
* _Rely on the default validation event
handler +
_ The default handler will fail on the first error or fatal error
encountered.
* _Implement and register a custom
validation event handler +
_ Client applications that require sophisticated event processing can
implement the _ValidationEventHandler_ interface and register it with
the Validator or Unmarshaller instance respectively.
* _Request an error/warning event list after
the operation completes +
_ By registering the _ValidationEventCollector_ helper, a specialized
event handler, with the _setEventHandler_ method, the _ValidationEvent_
objects created during the unmarshal and marshal operations are
collected. The client application can then request the list after the
operation completes.
Validation events are handled differently
depending on how the client application is configured to process them as
described previously. However, there are certain cases where a JAXB
implementation may need to indicate that it is no longer able to
reliably detect and report errors. In these cases, the JAXB
implementation will set the severity of the _ValidationEvent_ to
_FATAL_ERROR_ to indicate that the _unmarshal_ or _validate_ operation
should be terminated. The default event handler and
_ValidationEventCollector_ helper class must terminate processing after
being notified of a fatal error. Client applications that supply their
own _ValidationEventHandler_ should also terminate processing after
being notified of a fatal error. If not, unexpected behavior may occur.
=== Unmarshalling
The _Unmarshaller_ class governs the process
of deserializing XML data into a Java content tree, capable of
validating the XML data as it is unmarshalled. It provides the basic
unmarshalling methods:
public interface Unmarshaller \{
ValidationEventHandler _getEventHandler_ ()
void _setEventHandler_
(ValidationEventHandler)
java.lang.Object
_getProperty_ (java.lang.String name) +
void _setProperty_ (java.lang.String name,
java.lang.Object value) +
+
void setSchema(javax.xml.validation.Schema schema)
javax.xml.validation.Schema getSchema()
UnmarshallerHandler _getUnmarshallerHandler_
() +
+
void setListener(Unmarshaller.Listener); +
Unmarshaller.Listener getListener();
+
java.lang.Object _unmarshal_ (java.io.File)
java.lang.Object _unmarshal_ (java.net.URL)
java.lang.Object
unmarshal(java.io.InputStream) +
java.lang.Object _unmarshal_ (org.xml.sax.InputSource) +
java.lang.Object _unmarshal_ (org.w3c.dom.Node) +
+
java.lang.Object
_unmarshal_ (javax.xml.transform.Source) +
java.lang.Object _unmarshal_ (javax.xml.stream.XMLStreamReader) +
java.lang.Object _unmarshal_ (javax.xml.stream.XMLEventReader) +
+
<T> JAXBElement<T> _unmarshal_ (org.w3c.dom.Node, +
Class<T> declaredType) +
<T> JAXBElement<T> _unmarshal_ (javax.xml.transform.Source, +
Class<T> declaredType) +
<T> JAXBElement<T> _unmarshal_ (javax.xml.stream.XMLStreamReader, +
Class<T> declaredType) +
<T> JAXBElement<T> _unmarshal_ (javax.xml.stream.XMLEventReader, +
Class<T> declaredType) +
}
The _JAXBContext_ class contains a factory to
create an _Unmarshaller_ instance. The _JAXBContext_ instance manages
the XML/Java binding data that is used by unmarshalling. If the
_JAXBContext_ object that was used to create an _Unmarshaller_ does not
know how to unmarshal the XML content from a specified input source,
then the _unmarshal_ operation will abort immediately by throwing an
_UnmarshalException_ . There are six convenience methods for
unmarshalling from various input sources.
An application can enable or disable
unmarshal-time validation by enabling JAXP 1.3 validation via the
_setSchema(javax.xml.validation.Schema)_ method. The application has the
option to customize validation error handling by overriding the default
event handler using the _setEventHandler(ValidationEventHandler)._ The
default event handler aborts the unmarshalling process when the first
validation error event is encountered. Validation processing options are
presented in more detail in link:jaxb.html#a326[See General
Validation Processing].”
An application has the ability to specify a
SAX 2.0 parser to be used by the _unmarshal_ operation using the
_unmarshal(javax.xml.transform.Source)_ method. Even though the JAXB
provider’s default parser is not required to be SAX2.0 compliant, all
providers are required to allow an application to specify their own
SAX2.0 parser. Some providers may require the application to specify the
SAX2.0 parser at binding compile time. See the method javadoc
_unmarshal(Source)_ for more detail on how an application can specify
its own SAX 2.0 parser.
The _getProperty_ / _setProperty_ methods
introduce a mechanism to associate implementation specific
property/value pairs to the unmarshalling process. At this time there
are no standard JAXB properties specified for the unmarshalling process.
=== Unmarshal event callbacks
The _Unmarshaller_ provides two styles of
callback mechanisms that allow application specific processing during
key points in the unmarshalling process. In 'class-defined' event
callbacks, application specific code placed in JAXB mapped classes is
triggered during unmarshalling. External listeners allow for centralized
processing of unmarshal events in one callback method rather than by
type event callbacks. The 'class defined' and external listener event
callback methods are independent of each other, both can be called for
one event. The invocation ordering when both listener callback methods
exist is defined in _jakarta.xml.bind.Unmarshaller.Listener_ javadoc.
Event callback methods should be written with
following considerations. Each event callback invocation contributes to
the overall unmarshal time. An event callback method throwing an
exception terminates the current unmarshal process.
=== Class-defined
A JAXB mapped class can optionally implement
the following unmarshal event callback methods.
_private void
beforeUnmarshal(Unmarshaller, +
Object parent)_
This method is called immediately after the
object is created and before the unmarshalling of this object begins.The
callback provides an opportunity to initialize JavaBean properties prior
to unmarshalling.
_Parameters:_
unmarshaller - unmarshal context.
parent - points to the parent object to which
this object will be set. Parent is null when this object is the root
object.
_private void afterUnmarshal(Unmarshaller, +
Object parent)_
This method is called after all the
properties (except IDREF) are unmarshalled for this object, but before
this object is set to the parent object.
_Parameters:_
unmarshaller - unmarshal context.
parent - points to the parent object to which
this object will be set. Parent is null when this object is the root
object.
These callback methods allow an object to
perform additional processing at certain key point in the unmarshalling
operation.
=== External Listener
The external listener callback mechanism
enables the registration of a _Unmarshaller.Listener_ instance with an
_Unmarshaller.setListener(Unmarshaller.Listener)_ . The external
listener receives all callback events, allowing for more centralized
processing than per class defined callback methods. The external
listener receives events when unmarshalling to a JAXB element or to JAXB
mapped class.
=== [[a379]]Unmarshalling Modes
There exist numerous use cases requiring the
ability to unmarshal invalid XML content. A flexible unmarshalling mode
is described in this version of the specification to enable predictable
unmarshalling of invalid content. The previous unmarshalling mode
implied by JAXB 1.0 specification is named structural unmarshalling.
This unmarshalling mode was well defined for the unmarshalling of valid
XML content and allowed an implementation to handle invalid XML content
in anyway that it choose to.
Both of these modes have benefits and
drawbacks based on an application’s xml processing needs.
=== Structural Unmarshalling
Some of the XML Schema to Java bindings in
JAXB 1.0 implied that an unmarshaller had to maintain a state machine,
implying that the order of elements had to match up exactly as described
by the schema or unmarshaller would work unpredictably. When this
unmarshalling process detects a structural inconsistency that it is
unable to recover from, it should abort the unmarshal process by
throwing Un _marshalException_ .
For example, it was valid for a JAXB
implementation to rigidly give up unmarshalling an invalid XML document
once it came across an unexpected element/attribute or missed a required
element or attribute. This mode appeals to users who prefer to be
notified that an xml document is deviating from the schema.
XML Schema to Java binding for interfaces and
implementation classes, link:jaxb.html#a536[See Java Content
Interface], can implement either structural unmarshalling or flexible
unmarshalling.
=== [[a386]]Flexible Unmarshalling
To address the rigidness of structural
unmarshalling, flexible unmarshalling mode is specified to enable
greater predictability in unmarshalling invalid XML content. It
unmarshals xml content by element name, rather than strictly on the
position of the element within a content model. This allows this mode to
handle the following cases:
* elements being out of order in a content
model
* recovering from required
elements/attributes missing from an xml document
* ignoring unexpected elements/attributes in
an xml document
In order to enable this mode, the following
JAXB 1.0 customized bindings that required state-driven unmarshalling
have been removed from this specification.
* Binding a model group or model group
definition to a Java class. +
Since there is no XML infoset information denoting these schema
components, a model group can only be inferred by applying positional
schema constraints to a valid XML document, tracking position within a
valid content model.
* Multiple occurrences of an element name in
a content model can no longer be mapped to different JAXB properties.
Instead the entire content model is bound to a general content model.
The removal of these bindings greatly assists
the error recovery for structural unmarshalling mode.
Flexible unmarshalling appeals to those who
need to be able to perform best match unmarshalling of invalid xml
documents.
The flexible unmarshalling process is
annotation driven. This process is specified in
link:jaxb.html#a3855[See Appendix],
link:jaxb.html#a3856[See Runtime Processing]”. Flexible
unmarshalling is required for JAXB annotated classes.
=== [[a397]]Marshalling
The _Marshaller_ class is responsible for
governing the process of serializing a Java content tree into XML data.
It provides the basic marshalling methods:
interface Marshaller \{
static final string JAXB_ENCODING;
static final string JAXB_FORMATTED_OUTPUT;
static final string JAXB_SCHEMA_LOCATION;
static final string
JAXB_NO_NAMESPACE_SCHEMA_LOCATION; +
static final string JAXB_FRAGMENT;
<PROTENTIALLY MORE PROPERTIES...> +
+
java.lang.Object
_getProperty_ (java.lang.String name) +
void _setProperty_
(java.lang.String name, java.lang.Object value) +
void _setEventHandler_
(ValidationEventHandler handler)
ValidationEventHandler _getEventHandler_ ()
void setSchema(javax.xml.validation.Schema
schema)
javax.xml.validation.Schema getSchema()
+
void setListener(Unmarshaller.Listener) +
Unmarshaller.Listener getListener()
+
void _marshal_ (java.lang.Object e, java.io.Writer writer) +
void _marshal_ (java.lang.Object e, java.io.OutputStream os) +
void _marshal_ (java.lang.Object e, org.xml.sax.ContentHandler)
void _marshal_ (java.lang.Object e, javax.xml.transform.Result)
void _marshal_ (java.lang.Object e, org.w3c.dom.Node) +
void _marshal_ (java.lang.Object e, +
javax.xml.stream.XMLStreamWriter writer)
org.w3c.dom.Node _getNode_ (java.lang.Object
contentTree) +
}
The _JAXBContext_ class contains a factory to
create a _Marshaller_ instance. Convenience method overloading of the
_marshal()_ method allow for marshalling a content tree to common Java
output targets and to common XML output targets of a stream of SAX2
events or a DOM parse tree.
Although each of the marshal methods accepts
a _java.lang.Object_ as its first parameter, JAXB implementations are
not required to be able to marshal any arbitrary _java.lang.Object_ . If
the first parameter is not a JAXB element, as determined by
_JAXBIntrospector.isElement()_ method, the marshal operation must throw
a _MarshalException_ . There exist two mechanisms to enable marshalling
an instance that is not a JAXB element. One method is to wrap the
instance as the value of a _jakarta.xml.bind.JAXBElement_ instance, and
pass the wrapper element as the first parameter to a _marshal_ method.
For java to schema binding, it is also possible to simply annotate the
instance's class with the appropriate program annotation,
_@XmlElementRoot_ , specified in Section 8.
The marshalling process can optionally be
configured to validate the content tree being marshalled. An application
can enable or disable marshal-time validation by enabling JAXP 1.3
validation via the _setSchema(javax.xml.validation.Schema)_ method. The
application has the option to customize validation error handling by
overriding the default event handler using the
_setEventHandler(ValidationEventHandler)._ The default event handler
aborts the marshalling process when the first validation error event is
encountered. Validation processing options are presented in more detail
in link:jaxb.html#a326[See General Validation Processing].”
There is no requirement that the Java content
tree be valid with respect to its original schema in order to marshal it
back into XML data. If the marshalling process detects a structural
inconsistency during its process that it is unable to recover from, it
should abort the marshal process by throwing _MarshalException_ . The
marshalling process of a JAXB-annotated class is annotation driven. This
process is specified in link:jaxb.html#a3855[See Appendix],
link:jaxb.html#a3856[See Runtime Processing]”.
=== Marshal event callbacks
The Marshaller provides two styles of
callback mechanisms that allow application specific processing during
key points in the marshalling process. In class-defined event callbacks,
application specific code placed in JAXB mapped classes is triggered
during marshalling. External listeners allow for centralized processing
of marshal events in one callback method rather than by type event
callbacks. The invocation ordering when both listener callback methods
exist is defined in _jakarta.xml.bind.Marshaller.Listener_ javadoc.
Event callback methods should be written with
following considerations. Each event callback invocation contributes to
the overall marshal time. An event callback method throwing an exception
terminates the current marshal process.
=== Class-defined
A JAXB mapped class can optionally implement
the following marshal event callback methods.
_private void beforeMarshal(Marshaller)_
This method is called before the marshalling
of this object starts.
_Parameters:_
marshaller - marshal context.
_private void afterMarshal(Marshaller)_
This method is called after the marshalling
of this object (and all its descendants) has finished.
_Parameters:_
marshaller - marshal context.
These callback methods allow the
customization of an JAXB mapped class to perform additional processing
at certain key point in the marshalling operation. The 'class defined'
and external listener event callback methods are independent of each
other, both can be called for one event.
An event callback method throwing an
exception terminates the current marshal process.
=== External Listener
The external listener callback mechanism
enables the registration of a _Marshaller_ . _Listener_ instance with a
_Marshaller.setListener(Marshaller.Listener)_ . The external listener
receives all callback events, allowing for more centralized processing
than per class-defined callback methods.
=== Marshalling Properties
The following subsection highlights
properties that can be used to control the marshalling process. These
properties must be set prior to the start of a marshalling operation:
the behavior is undefined if these attributes are altered in the middle
of a marshalling operation. The following standard properties have been
identified:
* _jaxb.encoding_ _:_ output character
encoding. If the property is not specified, it defaults to "UTF-8".
* _jaxb.formatted.output_ : +
_true_ - human readable indented xml data +
_false_ - unformatted xml data +
If the property is not specified, it defaults to _false_ .
* _jaxb.schemaLocation +
_ This property allows the client application to specify an
_xsi:schemaLocation_ attribute in the generated XML data.
* _jaxb.noNamespaceSchemaLocation +
_ This property allows the client application to specify an
_xsi:noNamespaceSchemaLocation_ attribute in the generated XML data.
* _jaxb.fragment +
_ Its value must be a java.lang.Boolean. This property determines
whether or not document level events will be generated by the
Marshaller. If this property is not defined, it defaults to _false_ .
=== JAXBIntrospector
This class provides access to key XML mapping
information of a JAXB mapped instance.
public abstract class JAXBIntrospector \{ +
public boolean isElement(Object jaxbObj); +
public QName getElementName(Object jaxbElement);
public static Object getValue(Object
jaxbElement);
}
The JAXB 2.0 architecture has two uniquely
different ways to represent an XML element.The XML Schema to Java
binding for an XML element declaration is described in
link:jaxb.html#a642[See Java Element Representation]”. The Java
to XML Schema binding for an XML element declaration is described in
Section 8.8.2, “@XmlRootElement.“
Use JAXBInstrospector.isElement(Object)
method to determine if an instance of a JAXB mapped class represents an
XML element. One can get the xml element tag name associated with a JAXB
element using _JAXBIntrospector.getElementName_ method.One can an xml
element’s value using getValue method. The getValue method normalizes
access of JAXB element, hiding whether the JAXB element is an instance
of jakarta.xml.bind.JAXBElement or if it is an JAXB element via an
@XmlRootElement class annotation.
=== Validation Handling
Methods defined in the binding framework can
cause validation events to be delivered to the client application’s
_ValidationEventHandler_ . _Setter_ methods generated in schema-derived
classes are capable of throwing _TypeConstraintExceptions_ , all of
which are defined in the binding framework.
The following list describes the primary
event and constraint-exception classes:
* An instance of a _TypeConstraintException_
subclass is thrown when a violation of a dynamically-checked type
constraint is detected. Such exceptions will be thrown by property-set
methods, for which it would be inconvenient to have to handle checked
exceptions; type-constraint exceptions are therefore unchecked, _i.e_ ,
this class extends _java.lang.RuntimeException_ . The constraint check
is always performed prior to the property-set method updating the value
of the property, thus if the exception is thrown, the property is
guaranteed to retain the value it had prior to the invocation of the
property-set method with an invalid value. This functionality is
optional to implement in this version of the specification.
Additionally, a customization mechanism is provided to control enabling
and disabling this feature.
* An instance of a _ValidationEvent_ is
delivered whenever a violation is detected during optionally enabled
unmarshal/marshal validation. Additionally, _ValidationEvents_ can be
discovered during marshalling such as ID/IDREF violations and print
conversion failures. These violations may indicate local and global
structural constraint violations, type conversion violations, type
constraint violations, etc.
* Since the unmarshal operation involves
reading an input document, lexical well-formedness errors may be
detected or an I/O error may occur. In these cases, an
_UnmarshalException_ will be thrown to indicate that the JAXB provider
is unable to continue the unmarshal operation.
* During the marshal operation, the JAXB
provider may encounter errors in the Java content tree that prevent it
from being able to complete. In these cases, a _MarshalException_ will
be thrown to indicate that the marshal operation can not be completed.
=== DOM and Java representation Binding
The Binder class is responsible for
maintaining the relationship between a infoset preserving view of an XML
document with a possibly partial binding of the XML document to a JAXB
representation. Modifications can be made to either the infoset
preserving view or the JAXB representation of the document while the
other view remains unmodified. The binder is able to synchronize the
changes made in the modified view back into the read-only view. When
synchronizing changes to JAXB view back to related xml infoset
preserving view, every effort is made to preserve XML concepts that are
not bound to JAXB objects, such as XML infoset comments, processing
instructions, namespace prefix mappings, etc.
=== Use Cases
* Read-only partial binding. +
+
Application only needs to manipulate a small part of a rather large XML
document. It suffices to only map the small of the large document to the
JAXB Java representation. +
* Updateable partial binding +
+
The application receives an XML document that follows a later version of
the schema than the application is aware of. The parts of the schema
that the application needs to read and/or modify have not changed. Thus,
the document can be read into an infoset preserving representation, such
as DOM, only bind the part of the document that it does still have the
correct schema for into the JAXB Java representation of the fragment of
the document using Binder.unmarshal from the DOM to the JAXB view.
Modify the partial Java representation of the document and then
synchronize the modified parts of the Java representation back to the
DOM view using _Binder.updateXML_ method.
* XPATH navigation +
+
Given that binder maintains a relationship between XML infoset view of
document and JAXB representation, one can use JAXP 1.3 XPATH on the XML
infoset view and use the binder’s associative mapping to get from the
infoset node to JAXB representation.
=== jakarta.xml.bind.Binder
The class _jakarta.xml.bind.Binder_ associates
an infoset preserving representation of the entire XML document with a
potentially partial binding to a Java representation. The binder
provides operations to synchronize between the two views that it is
binding.
public abstract class Binder<XmlNode> \{ +
_// Create two views of XML content, infoset view and JAXB view +
_ public abstract Object unmarshal(XmlNode) +
<T> JAXBElement<T> unmarshal(org.w3c.dom.Node, +
Class<T> declaredType)
public abstract void marshal(Object
jaxbObjcet, XmlNode) +
+
_//Navigation between xml infoset view and JAXB view. +
_ public abstract XmlNode getXMLNode(Object jaxbObject ); +
public abstract Object getJAXBNode(XmlNode); +
+
_// Synchronization methods_
public abstract XmlNode updateXML(Object
jaxbObject ) +
public abstract XmlNode updateXML(Object jaxbObject, XmlNode)
throws JAXBException; +
public abstract Object updateJAXB( XmlNode) +
throws JAXBException; +
+
_// Enable optional validation +
_ public abstract void setSchema(Schema); +
public abstract Schema getSchema(); +
public abstract void setEventHandler( ValidationEventHandler) +
throws JAXBException; +
public abstract ValidationEventHandler getEventHandler() +
throws JAXBException; +
+
_// Marshal/Unmarshal properties +
_ public abstract void setProperty(String name, Object value) +
throws PropertyException; +
public abstract Object getProperty(String name) +
throws PropertyException;
}
== CHAPTER 5 -
Java
Representation of XML Content
This section defines the basic binding
representation of package, value class, element classes, properties and
enum type within the Java programming language. Each section briefly
states the XML Schema components that could be bound to the Java
representation. A more rigorous and thorough description of possible
bindings and default bindings occurs in link:jaxb.html#a694[See
Binding XML Schema to Java Representations]” and in
link:jaxb.html#a1498[See Customizing XML Schema to Java
Representation Binding].”
=== Mapping between XML Names and Java Identifiers
XML schema languages use _XML names_ , _i.e._
, strings that match the Name production defined in XML 1.0 (Second
Edition) to label schema components. This set of strings is much larger
than the set of valid Java class, method, and constant identifiers.
link:jaxb.html#a4649[See Appendix], “Binding XML Names to Java
Identifiers,” specifies an algorithm for mapping XML names to Java
identifiers in a way that adheres to standard Java API design
guidelines, generates identifiers that retain obvious connections to the
corresponding schema, and results in as few collisions as possible. It
is necessary to rigorously define a standard way to perform this mapping
so all implementations of this specification perform the mapping in the
same compatible manner.
=== [[a482]]Java Package
Just as the target XML namespace provides a
naming context for the named type definitions, named model groups,
global element declarations and global attribute declarations for a
schema vocabulary, the Java package provides a naming context for Java
interfaces and classes. Therefore, it is natural to map the target
namespace of a schema to be the package that contains the Java value
class representing the structural content model of the document.
A package consists of:
* A _name_ , which is either derived directly
from the XML namespace URI as specified in
link:jaxb.html#a4788[See Generating a Java package name]” or
specified by a binding customization of the XML namespace URI as
described in link:jaxb.html#a1674[See package].”
* A set of Java value class representing the
content models declared within the schema.
* A set of Java element classes representing
element declarations occurring within the schema.
link:jaxb.html#a642[See Java Element Representation]” describes
this binding in more detail.
* A public class _ObjectFactory_ contains:
* An instance factory method signature for
each Java content within the package. +
+
Given Java value class named Foo, here is the derived factory method:
+
public Foo createFoo();
* An element instance factory method
signature for each bound element declaration.
+
public JAXBElement<T> createFoo(T elementValue);
* Dynamic instance factory allocator method
signature:
+
public Object newInstance(Class javaContentInterface); +
* Property setter/getter +
Provide the ability to associate implementation specific property/value
pairs with the instance creation process.
java.lang.Object _getProperty_ (String
name); +
void _setProperty_ (String name, Object value);
* A set of enum types.
* Package javadoc.
=== Example:
Purchase Order Schema fragment with
_targetNamespace_ :
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema" +
xmlns:po="http://www.example.com/PO1" +
targetNamespace="http://www.example.com/PO1"> +
<xs:element name="purchaseOrder" type="po:PurchaseOrderType"/> +
<xs:element name="comment" type="xs:string"/> +
<xs:complexType name="PurchaseOrderType"/> +
... +
</xs:schema>
Default derived Java code:
import jakarta.xml.bind.JAXBElement; +
package com.example.PO1; +
public class PurchaseOrderType \{ .... }; +
public Comment \{ String getValue()\{...} void setValue(String)\{...}
} +
... +
public class ObjectFactory \{ +
PurchaseOrderType createPurchaseOrderType(); +
JAXBElement<PurchaseOrderType>
createPurchaseOrder(PurchaseOrderType
elementValue); +
Comment createComment(String value); +
... +
}
=== Enum Type
A simple type definition whose value space is
constrained by enumeration facets can be bound to a Java enum type. Enum
type was introduced in J2SE 5.0 and is described in Section 8.9 of
[JLS]. Enum type is a significant enhancement over the typesafe enum
design pattern that it was designed to replace. If an application wishes
to refer to the values of a class by descriptive constants and
manipulate those constants in a type safe manner, it should consider
binding the XML component containing enumeration facets to an enum type.
An enum type consists of:
* A _name_ , which is either computed
directly from an XML name or specified by a binding customization for
the schema component.
* A package name, which is either computed
from the target namespace of the schema component or specified within a
binding declaration as a customization of the target namespace or a
specified package name for components that are scoped to no target
namespace.
* Outer Class Names is “ _._ ” separated list
of outer class names.
By default, if the XML component containing a
typesafe enum class to be generated is scoped within a complex type as
opposed to a global scope, the typesafe enum class should occur as a
nested class within the Java value class representing the complex type
scope. +
Absolute class name is PackageName.[OuterClassNames.]Name. +
Note: Outer Class Name is null if class is a top-level class. +
+
The schema customization <jaxb:globalBindings localScoping=”toplevel”/>,
specified in Section link:jaxb.html#a1582[See Usage], disables
the generation of schema-derived nested classes and can be used to
override the default binding of a nested schema component binding to
nested Java class.
* A set of enum constants.
* Class javadoc is a combination of a
documentation annotation from the schema component and/or javadoc
specified by customization.
An enum constant consists of:
* A name, which is either computed from the
enumeration facet value or specified by customization.
* A _value_ for the constant. Optimally, the
_name_ is the same as the _value_ . This optimization is not possible
when the enumeration facet value is not a valid Java identifier.
* A datatype for the constant’s value.
* Javadoc for the constant field is a
combination of a documentation annotation for an enumeration value facet
and/or javadoc specified by customization.
=== Content Representation
A complex type definition is bound to either
a Java value class or a content interface, depending on the value of the
global binding customization _[jaxb:globalBinding]_
_@generateValueClass_ , specified in link:jaxb.html#a1582[See
Usage]”. Value classes are generated by default. The attributes and
children element content of a complex type definition are represented as
properties of the Java content representation. Property representations
are introduced in link:jaxb.html#a541[See Properties].
=== [[a521]]Value Class
A value class consists of:
* A _name_ , which is either computed
directly from an XML name or specified by a binding customization for
the schema component.
* A package name, which is either computed
from the target namespace of the schema component or specified by a
binding customization of the target namespace or a specified package
name for components that are scoped to no target namespace.
* The _outer class name_ context, a
dot-separated list of Java class names.
By default, if the XML schema component for
which a Java value class is to be generated is scoped within a complex
type as opposed to globally, the complex class should occur as a nested
class within the Java value class representing the complex type scope.
The schema customization <jaxb:globalBindings localScoping=”toplevel”/>,
specified in Section link:jaxb.html#a1582[See Usage], disables
the generation of schema-derived nested classes and all classes are
generated as toplevel classes.
The absolute class name is
PackageName.[OuterClassNames.]Name. +
Note: The OuterClassNames is null if the class is a top-level class.
* A base class that this class extends. See
link:jaxb.html#a917[See Complex Type Definition] for further
details.
* A set of Java properties providing access
and modification to the complex type definition’s attributes and content
model represented by the value class.
* Class-level javadoc is a combination of a
documentation annotation from the schema component and/or javadoc
specified within customization.
* Creation
* A value class supports creation via a
public constructor, either an explicit one or the default no-arg
constructor.
* A factory method in the package’s
_ObjectFactory_ class (introduced in link:jaxb.html#a482[See
Java Package]”). The factory method returns the type of the Java value
class. The name of the factory method is generated by concatenating the
following components: +
- The string constant _create_ . +
- If the Java value class is nested within another value class, +
then the concatenation of all outer Java class names. +
- The _name_ of the Java value class.
For example, a Java value class named _Foo_
that is nested within Java value class _Bar_ would have the following
factory method signature generated in the containing Java package’s
_ObjectFactory_ class:
Bar.Foo createBarFoo() \{...}
=== [[a536]]Java Content Interface
JAXB 1.0 bound a complex type definition to a
content interface. This binding is similar to the value class binding
with the following differences.
* A content interface is a public interface
while a value class is a public class.
* A content interface can only be created
with an ObjectFactory method whereas a value class can be created using
a public constructor. The factory method signature is the same for both
value class and content interface binding to ease switching between the
two binding styles.
* A content interface contains the method
signatures for the set of properties it contains, while a value class
contains method implementations.
=== [[a541]]Properties
The schema compiler binds local schema
components to _properties_ within a Java value class.
A property is defined by:
* A _name_ , which is either computed from
the XML name or specified by a binding customization for the schema
component.
* A _base type_ , which may be a Java
primitive type ( _e.g._ , _int_ ) or a reference type.
* An optional _predicate_ , which is a
mechanism that tests values of the base type for validity and throws a
_TypeConstraintException_ if a type constraint expressed in the source
schema is violated. link:#a5358[7]
* An optional _collection type_ , which is
used for properties whose values may be composed of more than one value.
* A _default value_ . Schema component has a
schema specified default value which is used when property’s value is
not set and not nil.
* Is _nillable_ . A property is nillable when
it represents a nillable element declaration.
A property is _realized_ by a set of _access
methods_ . Several property models are identified in the following
subsections; each adds additional functionally to the basic set of
access methods.
A property’s access methods are named in the
standard JavaBeans style: the name-mapping algorithm is applied to the
property name and then each method name is constructed by prefixing the
appropriate verb ( _get_ , _set_ , etc.).
[[a552]]A property is
said to have a set value if that value was assigned to it during
unmarshallinglink:#a5359[8] or by invoking its mutation method.
The _value_ of a property is its set value, if defined; otherwise, it is
the property’s schema specified default value, if any; otherwise, it is
the default initial value for the property’s base type as it would be
assigned for an uninitialized field within a Java
classlink:#a5360[9]. link:jaxb.html#50536473_21325[See All other
property kinds rely on the invocation of their set method with a value
of null to discard the set value of its property. Since this is not
possible for primitive types or a List property, the additional method
is generated for these cases illustrate the method invocations that
result in transitions between the possible states of a JAXB property
value.] link:jaxb.html#a623[See States of a Property
Value]link:jaxb.html#a623[See States of a Property Value]
illustrates the states of a JAXB property and the invocations that
result in state changes.
=== Simple Property
A non-collection property _prop_ with a base
type _Type_ is realized by the two methods
[width="100%",cols="100%",options="header",]
|===
|public Type get _Id_ ();
|public void set _Id_ (Type value);
|===
where _Id_ is a metavariable that represents
the Java method identifier computed by applying the name mapping
algorithm described in link:jaxb.html#a4656[See The Name to
Identifier Mapping Algorithm]” to prop. There is one exception to this
general rule in order to support the boolean property described in
[BEANS]. When _Type_ is boolean, the get _Id_ method specified above is
replaced by the method signature, _boolean_ is _Id_ ().
* The _get_ or _is_ method returns the
property’s value as specified in the previous subsection. If null is
returned, the property is considered to be absent from the XML content
that it represents.
* The _set_ method defines the property’s set
value to be the argument _value_ . If the argument value is _null_ , the
property’s set value is discarded. Prior to setting the property’s value
when TypeConstraint validation is enabledlink:#a5361[10], a non-
_null_ value is validated by applying the property’s predicate _._ If
_TypeConstraintException_ is thrown, the property retains the value it
had prior to the _set_ method invocation.
When the base type for a property is a
primitive non-reference type and the property’s value is optional, the
corresponding Java wrapper class can be used as the base type to enable
discarding the property’s set value by invoking the set method with a
null parameter. link:jaxb.html#a610[See isSet Property
Modifier] describes an alternative to using a wrapper class for this
purpose. The _[jaxb:globalBinding]_ customization _@optionalProperty_
controls the binding of an optional primitive property as described in
link:jaxb.html#a1582[See Usage].
=== Example
In the purchase order schema, the _partNum_
attribute of the _item_ element definition is declared:
<xs:attribute name="partNum" type="SKU"
use="required"/>
This element declaration is bound to a simple
property with the base type _java.lang.String_ :
public String getPartNum(); +
public void setPartNum(String x);
The _setPartNum_ method could apply a
predicate to its argument to ensure that the new value is legal, _i.e._
, that it is a string value that complies with the constraints for the
simple type definition, SKU _,_ and that derives by restriction from
_xs:string_ and restricts the string value to match the regular
expression pattern _"\d\{3}-[A-Z]\{2}"_ .
It is legal to pass _null_ to the
_setPartNum_ method even though the _partNum_ attribute declaration’s
attribute _use_ is specified as required. The determination if _partNum_
content actually has a value is a local structural constraint rather
than a type constraint, so it is checked during validation rather than
during mutation.
=== Collection Property
A collection property may take the form of an
_indexed property_ or a _list property_ . The base type of an indexed
property may be either a primitive type or a reference type, while that
of a list property must be a reference type.
A collection consists of a group of
collection items. If one of the collection items can represent a
nillable element declaration, setting a collection item to _null_ is
semantically equivalent to inserting a nil element, _xsi:nil=”true”_ ,
into the collection property. If none of the collection items can ever
represent a nillable element declaration, setting a collection item to
_null_ is the semantic equivalent of removing an optional element from
the collection property.
=== [[a572]]Indexed Property
This property follows the indexed property
design pattern for a multi-valued property from the JavaBean
specification. An indexed property _prop_ with base type _Type_ is
realized by the five methods
[width="100%",cols="100%",options="header",]
|===
|public _Type_ [] get _Id_ ();
|public void set _Id_ __ ( _Type_ [] value);
|public void set _Id_ (int index, _Type_
value);
|public _Type_ get _Id_ (int index); +
public int get _Id_ Length();
|===
regardless of whether _Type_ is a primitive
type or a reference type. _Id_ is computed from _prop_ as it was defined
in simple property. An array item is a specialization of the collection
item abstraction introduced in the collection property overview.
* get _Id_ () +
The array _getter_ method returns an array containing the property’s
value. If the property’s value has not set, then _null_ is returned.
* set _Id_ ( _Type_ [] _) +
_ The _array setter_ method defines the property’s set value. If the
argument itself is _null_ then the property’s set value, if any, is
discarded. If the argument is not _null_ and _TypeConstraint_ validation
is enabled link:#a5362[11] then the sequence of values in the
array are first validated by applying the property’s predicate, which
may throw a _TypeConstraintException_ . If the _TypeConstraintException_
is thrown, the property retains the value it had prior to the _set_
method invocation. The property’s value is only modified after the
_TypeConstraint_ validation step.
* set _Id_ (int, _Type_ ) +
The indexed _set_ ter method allows one to set a value within the array.
The runtime exception _java.lang.ArrayIndexOutOfBoundsException_ may be
thrown if the index is used outside the current array bounds. If the
value argument is non-null and TypeConstraint validation is enabled5,
the value is validated against the property’s predicate, which may throw
an unchecked _TypeConstraintException_ . If _TypeConstraintException_ is
thrown, the array index remains set to the same value it had before the
invocation of the indexed _setter_ method. When the array item
represents a nillable element declaration and the indexed setter value
parameter is null, it is semantically equivalent to inserting a nil
element into the array.
* get _Id_ (int) +
The indexed _get_ ter method returns a single element from the array.
The runtime exception _java.lang.ArrayIndexOutOfBoundsException_ may be
thrown if the index is used outside the current array bounds. In order
to change the size of the array, you must use the array set method to
set a new (or updated) array.
* get _Id_ Length() +
The indexed length method returns the length of the array. This method
enables you to iterate over all the items within the indexed property
using the indexed mutators exclusively. Exclusive use of indexed
mutators and this method enable you to avoid the allocation overhead
associated with array _getter_ and _setter_ methods.
The arrays returned and taken by these
methods are not part of the content object’s state. When an array
_getter_ method is invoked, it creates a new array to hold the returned
values. Similarly, when the corresponding array _setter_ method is
invoked, it copies the values from the argument array.
To test whether an indexed property has a set
value, invoke its _array getter_ method and check that the result is not
_null_ . To discard an indexed property’s set value, invoke its array
_setter_ method with an argument of _null_ .
See the customization attribute
_collectionType_ in link:jaxb.html#a1580[See <globalBindings>
Declaration]” and link:jaxb.html#a1783[See <property>
Declaration]” on how to enable the generation of indexed property
methods for a collection property.
=== Example
In the purchase order schema, we have the
following repeating element occurrence of element _item_ within
_complexType_ _Items_ .
<xs:complexType name= _"Items"_ >
<xs:sequence>
<xs:element name= _"item"_ minOccurs="1"
maxOccurs="unbounded"> +
<xs:complexType>...</xs:complexType> +
</xs:element> +
</xs:complexType>
The content specification of this element
type could be bound to an array property realized by these five methods:
public Items.ItemType[] getItem();
public void setItem(Items.ItemType[]
value); +
public void setItem(int index, Items.ItemType value); +
public Items.ItemType getItem(int index); +
public int getItemLength();
=== [[a595]]List Property
A list property _prop_ with base type _Type_
is realized by the method where _List_ is the interface _java.util.List_
, _Id_ is defined as above. If base type is a primitive type, the
appropriate wrapper class is used in its place.
[width="100%",cols="100%",]
|===
|public List<Type> get _Id_ ();
|===
* The _get_ method returns an object that
implements the _List<Type>_ interface, is mutable, and contains the
values of type _Type_ that constitute the property’s value. If the
property does not have a set value or a schema default value, a zero
length _java.util.List_ instance is returned.
The _List_ returned by the _get_ method is a
component of the content object’s state. Modifications made to this list
will, in effect, be modifications to the content object. If
_TypeConstraint_ validation is enabled, the list’s mutation methods
apply the property’s predicate to any non- _null_ value before adding
that value to the list or replacing an existing element’s value with
that value; the predicate may throw a _TypeConstraintException_ . The
collection property overview discussion on setting a collection item to
null specifies the meaning of inserting a null into a List.
The _unset_ method introduced in
link:jaxb.html#a610[See isSet Property Modifier] enables one to
discard the set value for a List property.
*
=== Example
The content specification of the _item_
element type could alternatively be bound to a list property realized by
one method:
public List<Item> getItem();
The list returned by the _getItem_ method
would be guaranteed only to contain instances of the _Item_ class. As
before, its length would be checked only during validation, since the
requirement that there be at least one _item_ in an element instance of
complex type definition _Items_ is a structural constraint rather than a
type constraint.
=== Constant Property
An attribute use named prop with a schema
specified fixed value can be bound to a Java constant value. _Id_ is
computed from _prop_ as it was defined in simple property. The value of
the fixed attribute of the attribute use provides the _<fixedValue>_
constant value.
[width="100%",cols="100%",]
|===
|static final public _Type_ ID =
<fixedValue>;
|===
The binding customization attribute
_fixedAttributeToConstantProperty_ enables this binding style.
link:jaxb.html#a1580[See <globalBindings> Declaration]” and
link:jaxb.html#a1783[See <property> Declaration]” describe how
to use this attribute.
=== [[a610]] _isSet_ Property Modifier
This optional modifier augments a modifiable
property to enable the manipulation of the property’s value as a set
value or a defaulted value. Since this functionality is above and beyond
the typical JavaBean pattern for a property, the method(s) associated
with this modifier are not generated by default.
link:jaxb.html#a1498[See Customizing XML Schema to Java
Representation Binding]” describes how to enable this customization
using the _generateIsSetMethod_ attribute.
The method signatures for the _isSet_
property modifier are the following:
[width="100%",cols="100%",]
|===
|public boolean _isSetId_ ();
|===
where _Id_ is defined as it was for simple
and collection property.
* The _isSet_ method returns _true_ if the
property has been set during unmarshalling or by invocation of the
mutation method _setId_ with a non- _null_ value.
link:#a5363[12]
To aid the understanding of what _isSet_
method implies, note that the unmarshalling process only unmarshals set
values into XML content.
A list property and a simple property with a
non-reference base type require an additional method to enable you to
discard the set value for a property:
[width="100%",cols="100%",]
|===
|public void _unsetId_ ();
|===
* The _unset_ method marks the property as
having no set value. A subsequent call to _getId_ method returns the
schema-specified default if it existed; otherwise, it returns the Java
default initial value for _Type_ .
All other property kinds rely on the
invocation of their set method with a value of null to discard the set
value of its property. Since this is not possible for primitive types or
a List property, the additional method is generated for these
caseslink:jaxb.html#a621[See All other property kinds rely on
the invocation of their set method with a value of null to discard the
set value of its property. Since this is not possible for primitive
types or a List property, the additional method is generated for these
cases illustrate the method invocations that result in transitions
between the possible states of a JAXB property value.] illustrate the
method invocations that result in transitions between the possible
states of a JAXB property
value.link:jaxb.html#a552[See A property is said to
have a set value if that value was assigned to it during unmarshalling
or by invoking its mutation method. The value of a property is its set
value, if defined; otherwise, it is the property’s schema specified
default value, if any; otherwise, it is the default initial value for
the property’s base type as it would be assigned for an uninitialized
field within a Java class. Figure 5.1 illustrates the states of a JAXB
property and the invocations that result in state
changes.][[a621]]
image:xmlb-8.png[image]
=== [[a623]]States of a Property Value
=== Example
In the purchase order schema, the _partNum_
attribute of the element _item_ ’s anonymous complex type is declared:
<xs:attribute name="partNum" type = "SKU"
use="required"/>
This attribute could be bound to a _isSet_
simple property realized by these four methods:
public String getPartNum(); +
public void setPartNum(String skuValue); +
public boolean isSetPartNum(); +
public void unsetPartNum();
It is legal to invoke the _unsetPartNum_
method even though the attribute’s _use_ is _“required”_ in the XML
Schema. That the attribute actually has a value is a local structural
constraint rather than a type constraint, so it is checked during
validation rather than during mutation.
=== [[a630]]Element Property
This property pattern enables the dynamic
association of an element name for a JAXB property. Typically, the
element name is statically associated with a JAXB property based on the
schema’s element name. Element substitution groups and wildcard content
allow an XML document author to use Element names that were not
statically specified in the content model of the schema. To support
these extensibility features, an application uses element property
setters/getters to dynamically introduce element names at runtime.
The method signatures for the _Element_
property pattern are the following:
[width="100%",cols="100%",]
|===
|public void set _Id_ ( _JAXBElement_ <?
extends _Type_ > value); +
public _JAXBElement_ <? extends _Type_ > get _Id_ ();
|===
where _Id_ and _Type_ are defined as they
were for simple and collection property. The fully qualified Java name
for _JAXBElement_ _<T>_ is _jakarta.xml.bind.JAXBElement<T>_ . The generic
types in the method signatures are expressed as a bounded wildcard to
support element substitution group, see details in
link:jaxb.html#a1023[See Element Declaration]”.
=== Property Summary
The following core properties have been
defined:
* Simple property - JavaBean design pattern
for single value property
* Indexed property - JavaBean design pattern
for multi-valued property
* List property - Leverages
java.util.Collection
* Constant property
The methods generated for these four core
property kinds are sufficient for most applications. Configuration-level
binding schema declarations enable an application to request finer
control than provided by the core properties. For example, the _isSet_
property modifier enables an application to determine if a property’s
value is set or not.
=== [[a642]]Java Element Representation
Based on rationale and criteria described in
link:jaxb.html#a1023[See Element Declaration], the schema
compiler binds an element declaration to a Java instance that implements
_jakarta.xml.bind.JAXBElement<T>_ . _JAXBElement<T>_ class provides access
to the basic properties of an XML element: its name, the value of the
element’s datatype, and whether the element’s content model is set to
nil, i.e. _xsi:nil=”true”_ . Optional properties for an Xml element that
corresponds to an element declaration from a known schema include the
element declaration’s declared type and scope.
The enhanced, default binding for an element
declaration only generates a element instance factory method and is
described in link:jaxb.html#a645[See Named Java Element
instance]”.link:#a5364[13] The customized binding that generates
a schema-dervied Element class for an element declaration is described
in link:jaxb.html#a657[See Java Element Class]”.
=== [[a645]]Named Java Element instance
Based on the normative binding details
described in link:jaxb.html#a1040[See Bind to JAXBElement<T>
Instance], the schema compiler binds an element declaration to an
element instance factory method.
The following is a generic element factory
signature.
package _elementDeclarationTargetNamespace_ ;
class ObjectFactory \{
jakarta.xml.bind.JAXBElement< _ElementType_ >
create _ElementName_ ( _ElementType_ __
value);
}
The element factory method enables an
application to work with elements without having to directly know the
precise _javax.xml.namespace.QName_ . The element factory method
abstraction sets the Xml element name with the Java representation of
the element, thus shielding the JAXB user from the complexities of
manipulating namespaces and QNames.
=== Binding of global element declaration to element factory
+
<xs:schema targetNamespace=”a” xmlns:a=”a”/> +
<xs:element name=”Foo” type=”xsd:int”/>
+
class ObjectFactory \{ +
// returns JAXBElement with its name set to QName(“a”, “Foo”). +
JAXBElement<Integer> createFoo(Integer value); +
}
=== [[a657]]Java Element Class
Based on criteria to be identified in
link:jaxb.html#a1068[See Bind to Element Class], the schema
compiler binds an element declaration to a Java element class. An
element class is defined in terms of the properties of the
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
* An element class name is generated from the
element declaration’s name using the XML Name to Java identifier name
mapping algorithm specified in link:jaxb.html#a4656[See The Name
to Identifier Mapping Algorithm].
* Scope of element class
* Global element declarations are declared in
package scope.
* By default, local element declarations
occur in the scope of the first ancestor complex type definition that
contains the declaration. The schema customization <jaxb:globalBindings
localScoping=”toplevel”/>, specified in Section
link:jaxb.html#a1582[See Usage], disables the generation of
schema-derived nested classes and all classes are generated as toplevel
classes.
* Each generated Element class must extend
the Java class _jakarta.xml.bind.JAXBElement<T>_ . The type T of the
_JAXBElement<T>_ is derived from the element declaration’s type.
Anonymous type definition binding is a special case that is specified in
link:jaxb.html#a1084[See Binding of an anonymous complex type
definition]
* A factory method is generated in the
package’s _ObjectFactory_ class introduced in
link:jaxb.html#a482[See Java Package].” The factory method
returns JAXBElement _<T>_ . The factory method has one parameter that is
of type _T_ . The name of the factory method is generated by
concatenating the following components:
* The string constant _create_ .
* If the Java element class is nested within
a value class, then the concatenation of all outer Java class names.
* The _name_ of the Java value class.
The returned instance has the Xml Element
name property set to the QName representing the element declaration’s
name.
For example, a Java element class named _Foo_
that is nested within Java value class _Bar_ would have the following
factory method generated in the containing Java package’s
_ObjectFactory_ class:
JAXBElement<Integer> createBarFoo(Integer
value)
* A public no-arg constructor is generated. +
The constructor must set the appropriate Xml element name, just as the
element factory method does.
* The Java element representation extends
JAXBElement _<T>_ class, its properties provide the capability to
manipulate
* the value of the element’s content +
Xml Schema’s type substitution capability is enabled by this property.
* whether the element’s content model is
_nil_
=== Example:
Given a complex type definition with mixed
content:
<xs:complexType name="AComplexType"
mixed=”true”>link:#a5364[14] +
<xs:sequence> +
<xs:element name="ASimpleElement"
type="xs:int"/>link:#a5366[15] +
</xs:sequence> +
</xs:complexType>
Its Java representation:
public value class AComplexType \{ +
public class ASimpleElement extends +
jakarta.xml.bind.JAXBElement<Integer> \{ +
} +
... +
}; +
class ObjectFactory \{ +
AComplexType createAComplexType(); +
JAXBElement<Integer> +
createAComplexTypeASimpleElement(Integer value); +
... +
}
=== [[a680]]Java Element Representation Summary
Element declaration binding evolved in JAXB
v2.0 to support XML Schema type substitution. The following diagrams
illustrate the binding changes for the following schema fragment:
<xs:element name=”foo” type=”fooType”/>
=== JAXB 1.0 : isA Relationship between generated element interface and its type
image:xmlb-9.png[image]
=== JAXB 2.0: hasA Relationship between element instance and its type as described in link:jaxb.html#a645[See Named Java Element instance]”
image:xmlb-10.png[image]
=== JAXB 2.0: hasA Relationship between generated element class and its type as described in link:jaxb.html#a657[See Java Element Class]”
image:xmlb-11.png[image]
While a JAXB v1.0 Element interface
implemented its type’s interface, a JAXB v2.0 Element instance has a
composition relationship to the value of the element declaration’s type,
accessible via the _jakarta.xml.bind.JAXBElement<T>_ property _Value_ .
This change reflects the relationship that type substitution allows an
element declaration to be associated with many different datatypes, not
just the datatype that was defined statically within the schema.
An added benefit to the default binding
change is to reduce the overhead associated with always generating Java
Element classes for every global element declaration.In JAXB 1.0, an
interface was generated for every complex type definition and global
element declaration. In JAXB 2.0, a value class is generated for every
complex type definition and only a factory method needs to be generated
for each global element declaration.
=== Summary
The composition and relationships between the
Java components introduced in this section are reflected in the
following diagram.
=== UML diagram of Java Representationlink:#a5367[16]
image:xmlb-12.png[image]
=== UML diagram when xs:element is bound to schema-derived Element class
image:xmlb-13.png[image]
See also link:jaxb.html#UNKNOWN[See
Summarize default XSD to Java binding for Figure 5.1 and Figure 5.2].
== CHAPTER 6 -
[[a694]]Binding
XML Schema to Java Representations
This chapter describes binding of XML schema
components to Java representations. The default binding is identified in
this chapter and the next chapter specifies the customizations that
override default binding.
=== Overview
The abstract model described in [XSD Part 1]
is used to discuss the default binding of each schema component type.
Each schema component is described as a list of properties and their
semantics. References to properties of a schema component as defined in
[XSD Part 1] are denoted using the notation \{schema property}
throughout this section. References to properties of information items
as defined in [XML-Infoset] are denoted by the notation [property].
All JAXB implementations are required to
implement the default bindings specified in this chapter. However, users
and JAXB implementors can use the global configuration capabilities of
the custom binding mechanism to override the defaults in a portable
manner.
For each binding of a schema component to its
Java representation, there is a description of Java mapping
annotation(s), described in link:jaxb.html#a2236[See Java Types
To XML]“, to be generated with the Java representation. The
standardization of these mapping annotations assist in specifying the
portability of a schema-derived JAXB-annotated classes. All JAXB
implementations are required to be able to unmarshal/marshal another
implementation’s schema-derived Java value classes by interpreting the
specified mapping annotations. Note that each mapping annotation is
described independent of whether it is the default mapping or a
customized mapping, JAXB implementations are allowed to optimize away
redundant mapping annotations that are the default mapping annotation.
*
All examples are non-normative. Note that in
the examples, the schema-derived code does not list all required mapping
annotations. In the interest of being terse, only the mapping
annotations directly connected to the schema component being discussed
are listed in its example.
=== [[a702]]Simple Type Definition
A schema component using a simple type
definition typically binds to a Java property. Since there are different
kinds of such schema components, the following Java property attributes
(common to the schema components) are specified here and include:
* base type
* collection type if any
* predicate
The rest of the Java property attributes are
specified in the schema component using the simple type definition.
While not necessary to perform by default,
this section illustrates how a simple type definition is bound to a JAXB
mapped class. This binding is necessary to preserve a simple type
definition referred to by _xsi:type_ attribute in an Xml instance
document. See link:jaxb.html#a1582[See Usage]“for the
customization that enables this binding.
=== Type Categorization
The simple type definitions can be
categorized as:
* schema built-in datatypes [XSD PART2]
* user-derived datatypes
Conceptually, there is no difference between
the two. A schema built-in datatype can be a primitive datatype. But it
can also, like a user-derived datatype, be derived from a schema
built-in datatype. Hence no distinction is made between the schema
built-in and user-derived datatypes.
The specification of simple type definitions
is based on the abstract model described in Section 4.1, “Simple Type
Definition” [XSD PART2]. The abstract model defines three varieties of
simple type definitions: atomic, list, union. The Java property
attributes for each of these are described next.
=== [[a715]]Atomic Datatype
If an atomic datatype has been derived by
restriction using an “enumeration” facet, the Java property attributes
are defined by link:jaxb.html#a829[See Enum Type].” Otherwise
they are defined as described here.
The base type is derived upon the XML
built-in type hierarchy [XSD PART2, Section 3] reproduced below.
image:xmlb-15.png[image]
=== XML Built-In Type Hierarchy
The above diagram is the same as the one in
[XSD PART2] except for the following:
* Only schema built-in atomic datatypes
derived by restriction have been shown.
* The schema built-in atomic datatypes have
been annotated with Java data types from the “Java Mapping for XML
Schema Built-in Types” table below.
*
The following is a mapping for subset of the
XML schema built-in data types to Java data types. This table is used to
specify the base type later.
=== [[a725]]Java Mapping for XML Schema Built-in Types
XML Schema Datatype
Java Datatype
_xsd:string_
_java.lang.String_
_xsd:integer_
_java.math.BigInteger_
_xsd:int_
_int_
_xsd.long_
_long_
_xsd:short_
_short_
_xsd:decimal_
_java.math.BigDecimal_
_xsd:float_
_float_
_xsd:double_
_double_
_xsd:boolean_
_boolean_
_xsd:byte_
_byte_
_xsd:QName_
_javax.xml.namespace.QName_ 1
_xsd:dateTime_
javax.xml.datatype.XMLGregorianCalendar 1
_xsd:base64Binary_
_byte[]_
_xsd:hexBinary_
_byte[]_
xsd:unsignedInt
long
xsd:unsignedShort
int
xsd:unsignedByte
short
xsd:time
javax.xml.datatype.XMLGregorianCalendar 1.
xsd:date
javax.xml.datatype.XMLGregorianCalendar 1.
xsd:g*
javax.xml.datatype.XMLGregorianCalendar 1.
{empty}xsd:anySimpleType +
(for xsd:element of this type)link:#a5368[17]
java.lang.Object
xsd:anySimpleType +
(for xsd:attribute of this type)
java.lang.String
xsd:duration
javax.xml.datatype.Duration 1
xsd:NOTATION
javax.xml.namespace.QName 1
1. JAXP 1.3 defines package
_javax.xml.datatype_ and _javax.xml.namespace_
The base type is determined as follows:
. Map by value space bounding facets +
If the simple type derives from or is _xsd:integer_ and has either a
constraining lower and/or upper bounds facet(s) or totalDigits facet,
check if the following optimized binding is possible:
. If the simple type derives from or is
_xsd:short_ , _xsd:byte_ or _xsd:unsignedByte_ , go to step 2.
. If the value space for the simple type is
representable in the range of _java.lang.Integer.MIN_VALUE_ and
_java.lang.Integer.MAX_VALUE_ , map to java primitive type, _int_ .
. If the value space for the simple type is
representable in the range of _java.lang.Long.MIN_VALUE_ and
_java.lang.Long.MAX_VALUE_ , map to java primitive type, _long_ .
. Else go to step 2.
. Map by datatype +
If a mapping is defined for the simple type in Table 6.1, the base type
defaults to its defined Java datatype.
. Map by base datatype +
Otherwise, the base type must be the result obtained by repeating the
step 1 and 2 using the \{base type definition}. For schema datatypes
derived by restriction, the \{base type definition} represents the
simple type definition from which it is derived. Therefore, repeating
step 1 with \{base type definition} essentially walks up the XML Schema
built-in type hierarchy until a simple type definition which is mapped
to a Java datatype is found.
The Java property predicate must be as
specified in “Simple Type Definition Validation Rules,” Section
4.1.4[XSD PART2].
=== Example:
The following schema fragment (taken from
Section 4.3.1, “Length” [XSD PART2]):
<xs:simpleType name="productCode"> +
<xs:restriction base="xs:string"> +
<xs:length value="8" fixed="true"/> +
</xs:restriction> +
</xs:simpleType>
The facet “length” constrains the length of a
product code (represented by _productCode_ ) to 8 characters (see
section 4.3.1 [XSD PART2] for details).
The Java property attributes corresponding to
the above schema fragment are:
* There is no Java datatype mapping for
_productCode._ So the Java datatype is determined by walking up the
built-in type hierarchy.
* The _\{base type definition}_ of
_productCode_ is _xs:string. xs:string_ is mapped to _java.lang.String_
(as indicated in the table, and assuming no customization). Therefore,
_productCode_ is mapped to the Java datatype _java.lang.String_ .
* The predicate enforces the constraints on
the length.
=== Notation
Given that the value space of _xsd:NOTATION_
is the set of _xsd:QName_ , bind _xsd:NOTATION_ type to
_javax.xml.namespace.QName_ .
For example, the following schema:
<xs:schema targetNamespace="http://e.org"
xmlns:e="http://e.org" +
xmlns:xs="http://www.w3.org/2001/XMLSchema"> +
<xs:notation name="jpeg" public="image/jpeg" system="jpeg.exe"/>
<xs:notation name="png" public="image/png" system="png.exe"/> +
<xs:simpleType name="pictureType"> +
<xs:restriction base="xs:NOTATION"> +
<xs:enumeration value="e:jpeg"/> +
<xs:enumeration value="e:png"/> +
</xs:restriction> +
</xs:simpleType> +
<xs:complexType name="Picture"> +
<xs:simpleContent> +
<xs:extension base="xs:hexBinary"> +
<xs:attribute name="format" type="e:pictureType"/>
</xs:extension> +
</xs:simpleContent> +
</xs:complexType> +
</xs:schema>
is mapped to the following Java code:
package org.e; +
import javax.xml.namespace.QName; +
public class Picture \{ +
void setValue(byte[] value) \{...} +
byte[] getValue() \{...} +
void setFormat(QName value)\{...} +
QName getFormat()\{...} +
}
With the following usage scenario:
Picture pic = ...; +
pic.setFormat(new QName("http://e.org","jpeg"));
=== [[a803]]Bind to a JAXB mapped class
By default, a named simple type definition is
not bound to a Java class. This binding is only necessary to enable the
precise type of an _xsi:type_ substitution to be preserved as described
in link:jaxb.html#a1158[See Type Substitution of a Simple Type
Definition]“. This binding is enabled via the global binding
customization attribute _@mapSimpleTypeDef_ specified in
link:jaxb.html#a1582[See Usage]“.
The binding of a named simple type definition
to a Java value class is based on the abstract model properties in
link:jaxb.html#a4867[See Simple Type Definition Schema
Component]. The Java value class must be defined as specified here,
unless the ref attribute is specified on the _<jaxb:class>_ declaration,
in which case the schema compiler will simply assume that the nominated
class is already bound to this simple type.
* _name:_ name is the Java identifier
obtained by mapping the XML name _\{name}_ using the name mapping
algorithm, specified in link:jaxb.html#a4656[See The Name to
Identifier Mapping Algorithm]. Note that anonymous simple type
definition’s are never bound to a Java value class.
* _package:_
* The schema-derived Java value class is
generated into the Java package that represents the binding of \{target
namespace}
* _outer class name:_
* There is no outer class name for a global
simple type definition.
* _base class:_
* Due to a constraint specified for @XmlValue
in Section 8, this class can not extend any other class. The derivation
by restriction hierarchy for simple type definitions can not be captured
in the schema-derived Java value class.
* _value property:_
* Same as the binding of simple content in
link:jaxb.html#a973[See Simple Content Binding] to an @XmlValue
annotated JAXB property.
The next two examples illustrate the binding
of a simple type definition to a Java value class when the appropriate
JAXB schema customization is enabled.
=== [[a816]]Simple type definition
<xs:simpleType name="productCode"> +
<xs:restriction base="xs:string"> +
<xs:length value="8" fixed="true"/> +
</xs:restriction> +
</xs:simpleType>
=== Binding of link:jaxb.html#a816[See Simple type definition]“
@XmlType(name="productCode") +
public class ProductCode \{ +
@XmlValue +
String getValue(); +
void setValue(String value); +
}
=== [[a820]]Annotations for standard XML datatypes
By default, a schema-derived JAXB property
bound from one of the following standard XML datatypes is annotated with
the specified mapping annotation.
[width="100%",cols="50%,50%",options="header",]
|===
| _Schema Type_ |
_JAXB Property Annotation_
|xsd:ID |@XmlID
|xsd:IDREF
|@XmlIDREF
|ref:swaRef
|@XmlAttachmentRef
|===
Note that JAXB schema customizations could
override these default binding.
=== [[a829]]Enum Type
The default mapping for a named atomic type
that is derived by restriction with enumeration facet(s) and whose
restriction base type (represented by \{base type definition}) is
_xs:String_ link:#a5369[18] or derived from it is mapped to an
enum type. The _[typesafeEnumBase]_ attribute customization described in
link:jaxb.html#a1580[See <globalBindings> Declaration]," enables
global configuration to alter what Xml built-in datatypes are bound by
default to an enum type. An anonymous simple type definition is never
bound to an enum class by default, but it can be customized as described
in link:jaxb.html#a2090[See <typesafeEnum> Declaration]” to bind
to an enum type.
=== Example binding
An example is provided first followed by a
more formal specification.
XML Schema fragment:
<xs:simpleType name="USState"> +
<xs:restriction base="xs:NCName"> +
<xs:enumeration value="AK"/> +
<xs:enumeration value="AL"/> +
</xs:restriction> +
</xs:simpleType>
The corresponding enum type binding is:
public enum USState \{ +
AK, AL; +
public String value() \{ return name(); } +
public static USState fromValue(String value) \{ ... } +
};
=== Enum type binding
The characteristics of an _enum type_ are
derived in terms of the properties of the
link:jaxb.html#a4867[See Simple Type Definition Schema
Component] as follows:
The enum type binding is defined as follows:
* name: The default name of the enum type,
enumType, is computed by applying the XML Name to Java identifier
mapping algorithm to the _\{name}_ of the simple type definition. There
is no mechanism to derive a name for an anonymous simple type
definition, the customization must provide the _name_ .
* package name: The package name is
determined from the _\{targetname space}_ of the schema that directly
contains the simple type definition.
* _outer class name:_
* There is no _outer class name_ for a global
simple type definition.
* There is no _outer class name_ when schema
customization, _[jaxb:globalBindings]_ _@localScoping_ , specified in
Section link:jaxb.html#a1582[See Usage], has a value of
_toplevel_ .
* The _outer class name_ for an anonymous
simple type definition is computed by traversing up the anonymous simple
type definition’s ancestor tree until the first ancestor is found that
is: +
- an XML component that is mapped to a Java value class, the _outer
class name_ is composed of the concatenation of this Java value class’s
_outer class name_ , “.” _,_ and its _name_ . +
- a global declaration or definition is reached. There is no _outer
class name_ for this case.
* _enum constants_ : Specified in next
section.
Note that since a Java enum type is
essentially a final class, it is not possible for it to be subclassed.
Thus, any derivations of a simple type definition bound to an enum type
can not be captured by an equivalent Java inheritance relationship.
The schema-derived enum is annotated, either
explicitly or by default mapping annotations, with the mapping
annotation @XmlEnum, specified in Section 8. The @XmlEnum annotation
elements are derived in terms of the abstract model properties for a
simple type definition summarized in link:jaxb.html#a4867[See
Simple Type Definition Schema Component] as follows:
=== Annotate enum type with @XmlEnum element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlEnum element
|@XmlEnum value
|name |simple type
definition's \{name}
|namespace
|\{target namespace}
|value |the java
type binding of the simple type definition’s _\{base type definition}_
|===
=== Enum Constant
An enum constant is derived for each
enumeration facet of the atomic type definition. The characteristics of
an enum constant of the enum type are derived in terms of the properties
of the link:jaxb.html#a4899[See Enumeration Facet Schema
Component] as follows:
* name: The name is either specified via
customization, _jaxb:typesafeEnumMember_ described in
link:jaxb.html#a2092[See Usage]“, or the name is computed as
specified in link:jaxb.html#a863[See XML Enumvalue-to-Java
Identifier Mapping]“.
* type: The Java type binding of the simple
type definition’s \{base_type_definition}.
* _value_ : The conversion of string
_\{value}_ to _type_ . _Value_ is manipulated via the following
generated enum type methods:
_public_ _type_ value(); +
public static _enumTypeName_ fromValue( _type_ value);
To assist an application in manipulating the
enum constants that comprise an enum type, all enum types have the
following two implicitly declared static methods as specified in Section
8.9 in [JLS3]. The enum type’s static method _values()_ returns an array
of all enum constants. The static method _valueOf(String name)_ returns
the enum constant represented by the name parameter.
=== XML Enumvalue-[[a863]]to-Java Identifier Mapping
The default name for the enum constant is
based on mapping of the XML enumeration value to a Java identifier as
described below.
The XML enumeration value _\{value}_ is
mapped to a Java Identifier using the algorithm specified in
link:jaxb.html#a4773[See Deriving a legal Java identifier from
an enum facet value]“.If there is a collision among the generated
constant fields _name_ or if it is not possible to generate a legal Java
identifier for one or more of the generated constant field names, see
link:jaxb.html#a1633[See @typesafeEnumMemberName]“for
customization options to resolve this error case.
=== Enum Constant Name differs from its Value
For all cases where there exist at least one
enumeration constant name that is not the same as the enumeration
constant’s value, the generated enum type must have a final value field
that is set by the enum type’s constructor. The code generation template
is the following:
=== At least one enum constant name differs from its value.
public enum _enumType_ \{ +
_EnumConstantName_ _1_ ( _EnumConstantValue_ _1_ ), +
... +
_EnumConstantName_ _X_ ( _EnumConstantValue_ _X)_ _; +
_ public _EnumConstantValueType_ value() \{ return value;} +
public static _enumType_ fromValue( _EnumConstantValueType_ val) +
\{ ... } +
+
final private _EnumConstantValueType_ value; +
private _enumType_ ( _EnumConstantValueType_ value) \{ +
this.value = value; +
} +
}
=== Code template when enum constant name is same as its enum constant value.
public enum _enumType_ \{ +
_EnumConstantName1_ , ..., _EnumConstantNameX_ ; +
public _Stringlink:#a5370[19]_ value() \{ return name();} +
public static _enumType_ fromValue( _String_ 1 value) \{ ... } +
}
The schema-derived enum constant is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation specified in Section 8. The _@XmlEnumValue_
annotation elements are derived in terms of the abstract model
properties for a enumerated facet summarized in
link:jaxb.html#a4899[See Enumeration Facet Schema Component] as
follows:
=== Annotate enum constant with @XmlEnumValue element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlEnumValue element
|@XmlEnumValue value
|value
|Enumeration facet’s \{value}
|===
=== Schema-derived enum type when enumeration facet’s value does not match enum constant name.
Given following schema fragment:
<xs:simpleType name="Coin"> +
<!-- Assume jaxb customization that binds Coin to an enumType--> +
<xs:restriction base="xs:int"> +
<!--Assume jaxb customization specifying enumConstantName--> +
<xs:enumeration value="1"/> <!-- name="penny"--> +
<xs:enumeration value="5"/> <!-- name="nickel"--> +
<xs:enumeration value="10"/><!-- name="dime"--> +
<xs:enumeration value="25"/><!-- name="quarter--> +
</xs:restriction> +
</xs:simpleType>
Schema-derived enum type:
@XmlEnum(value="java.lang.Integer.class") +
public enum Coin \{ +
@XmlEnumValue("1") PENNY(1), +
@XmlEnumValue("5") NICKEL(5), +
@XmlEnumValue("10") DIME(10), +
@XmlEnumValue("25") QUARTER(25); +
public int value()\{ return value; } +
public static Coin fromValue(int value) \{ ... } +
+
final private Integer value; +
Coin(int value) \{ this.value = value; } +
}
=== [[a883]]List
A list simple type definition can only
contain list items of atomic or union datatypes. The item type within
the list is represented by the schema property \{item type definition}.
The Java property attributes for a list
simple type definition are:
* The _base type_ is derived from the \{item
type definition} as follows. If the Java datatype for \{item type
definition} is a Java primitive type, then the base type is the wrapper
class for the Java primitive type. Otherwise, the Java datatype is
derived from the XML datatype as specified in
link:jaxb.html#a715[See Atomic Datatype]” and
link:jaxb.html#a829[See Enum Type].”
* The _collection type_ defaults to an
implementation of _java.util.List_ . Note that this specification does
not specify the default implementation for the interface
_java.util.List_ , it is implementation dependent.
* The _predicate_ is derived from the “Simple
Type Definition Validation Rules,” in section 4.1.4,[XSD PART2].
=== Example:
For the following schema fragment:
<xs:simpleType name="xs:USStateList">
<xs:list itemType="xs:string"/>
</xs:simpleType>
The corresponding Java property attributes
are:
* The _base type_ is derived from \{item type
definition} which is XML datatype, _“xs:string”_ , thus the Java
datatype is _java.util.String_ as specified in __
link:jaxb.html#a725[See Java Mapping for XML Schema Built-in
Types] _.”_
* The _collection type_ defaults to an
implementation of _java.util.List_ .
* The _predicate_ only allows instances of
_base type_ to be inserted into the list. When failfast check is being
performedlink:#a5370[20], the list’s mutation methods apply the
property’s predicate to any non- _null_ value before adding that value
to the list or replacing an existing element’s value with that value;
the predicate may throw a _TypeConstraintException_ .
The schema-derived property is annotated,
either explicitly or by default mapping annotations, with the mapping
annotation @XmlList, specified in Section 8.
=== [[a899]]Union Property
A union property _prop_ is used to bind a
union simple type definition schema component. A union simple type
definition schema component consists of union members which are schema
datatypes. A union property, is therefore, realized by:
[width="100%",cols="100%",options="header",]
|===
|public Type get _Id_ ();
|public void set _Id_ (Type value);
|===
where _Id_ is a metavariable that represents
the Java method identifier computed by applying the name mapping
algorithm described in link:jaxb.html#a4656[See The Name to
Identifier Mapping Algorithm] to _prop_ .
The _base type_ is String. If one of the
member types is derived by list, then the Union property is represented
as the appropriate collection property as specified by the customization
_<jaxb:globalBindings>_ _@collectionType_ value, specified in
link:jaxb.html#a1582[See Usage].”
* The _getId_ method returns the set value.
If the property has no set value then the value _null_ is returned. The
value returned is Type.
* The _setId_ method sets the set value. +
If value is _null_ , the property’s set value is discarded. Prior to
setting the property’s value when TypeConstraint validation is enabled,
a non- _null_ value is validated by applying the property’s predicate,
which may throw a _TypeConstraintException._ No setter is generated if
the union is represented as a collection property.
=== Example: Default Binding: Union
The following schema fragment:
<xs:complexType name="CTType"> +
<xs:attribute name="state" type="ZipOrName"/> +
</xs:complexType> +
<xs:simpleType name="ZipOrName" +
memberTypes="xs:integer xs:string"/>
+
is bound to the following Java representation.
public class CTType \{ +
String getState() \{...} +
void setState(String value) \{...} +
}
=== Union
A simple type definition derived by a union
is bound using the union property with the following Java property
attributes:
* the _base type_ as specified in
link:jaxb.html#a899[See Union Property].”
* if one of the member types is derived by
_<xs:list>_ , then the union is bound as a Collection property.
* The _predicate_ is the schema constraints
specified in “Simple Type Definition Validation Rules,” Section 4.1.4
[XSD PART2].
=== [[a917]]Complex Type Definition
=== [[a918]]Aggregation of Java Representation
A Java representation for the entire schema
is built based on aggregation. A schema component aggregates the Java
representation of all the schema components that it references. This
process is done until all the Java representation for the entire schema
is built. Hence a general model for aggregation is specified here once
and referred to in different parts of the specification.
The model assumes that there is a schema
component _SP_ which references another schema component _SC_ . The Java
representation of _SP_ needs to aggregate the Java representation of
_SC_ . There are two possibilities:
* _SC_ is bound to a property set.
* _SC_ is bound to a Java datatype or a Java
value class.
Each of these is described below.
=== Aggregation of Datatype/Class
If a schema component _SC_ is bound to a Java
datatype or a Java value class, then _SP_ aggregates _SC’s_ Java
representation as a simple property defined by:
* _name:_ the name is the class/interface
name or the Java datatype or a name determined by SP. The name of the
property is therefore defined by the schema component which is
performing the aggregation.
* _base type:_ If SC is bound to a Java
datatype, the base type is the Java datatype. If SC is bound to a Java
value class, then the base type is the class name, including a dot
separated list of class names within which SC is nested.
* _collection type:_ There is no collection
type.
* _predicate:_ There is no predicate.
=== [[a930]]Aggregation of Property Set
If _SC_ is bound to a property set, then _SP_
aggregates by adding _SC’s_ property set to its own property set.
Aggregation of property sets can result in
name collisions. A name collision can arise if two property names are
identical. A binding compiler must generate an error on name collision.
Name collisions can be resolved by using customization to change a
property name.
=== [[a933]]Java value class
{empty}The binding of a complex type
definition to a Java value class is based on the abstract model
properties in link:jaxb.html#a4907[See Complex Type Definition
Schema Component]. The Java value class must be defined as specified
here, unless the ref attribute is specified on the _<jaxb:class>_
customization, in which case the schema compiler will simply assume that
the nominated class is already bound to this complex
type.link:#a5372[21]
* _name:_ name is the Java identifier
obtained by mapping the XML name _\{name}_ using the name mapping
algorithm, specified in link:jaxb.html#a4656[See The Name to
Identifier Mapping Algorithm]. For the handling of an anonymous complex
type definition, see link:jaxb.html#a1084[See Binding of an
anonymous complex type definition]” for how a _name_ value is derived
from its parent element declaration.
* _package:_
* For a global complex type definition, the
derived Java value class is generated into the Java package that
represents the binding of \{target namespace}
* For the value of _package_ for an anonymous
complex type definition, see link:jaxb.html#a1084[See Binding of
an anonymous complex type definition]".
* _outer class name:_
* There is no outer class name for a global
complex type definition.
* link:jaxb.html#a1084[See Binding of
an anonymous complex type definition]" defines how to derive this
property from the element declaration that contains the anonymous
complex type definition.
* _base class:_ A complex type definition
can derive by restriction or extension (i.e. _\{derivation method}_ is
either “extension” or “restriction”). However, since there is no concept
in Java programming similar to restriction, both are handled the same.
If the _\{base type definition}_ is itself mapped to a Java value class
(Ci2), then the base class must be Ci2. This must be realized as: +
public class Ci1 extends Ci2 \{ +
..... +
}
See example of derivation by extension at the
end of this section.
* abstract: The generated Java class is
abstract when the complex type definition’s _\{abstract}_ property is
_true_ .
* _property set:_ The Java representation of
each of the following must be aggregated into Java value class’s
property set (link:jaxb.html#a918[See Aggregation of Java
Representation]”).
* A subset of _\{attribute uses}_ is
constructed. The subset must include the schema attributes corresponding
to the _<xs:attribute>_ children and the _\{attribute uses}_ of the
schema attribute groups resolved by the <ref> attribute. Every
attribute’s Java representation (link:jaxb.html#a1252[See
Attribute use]”) in the set of attributes computed above must be
aggregated.
* If the optional _\{attribute wildcard}_ is
present, either directly or indirectly, a property defined by
link:jaxb.html#a1306[See Attribute Wildcard]“is generated.
* The Java representation for _\{content
type}_ must be aggregated.
For a “Complex Type Definition with complex
content,” the Java representation for _\{content type}_ is specified in
link:jaxb.html#a1332[See Content Model - Particle, Model Group,
Wildcard].” +
For a complex type definition which is a “Simple Type Definition with
simple content,” the Java representation for _\{content type}_ is
specified in link:jaxb.html#a973[See Simple Content Binding].”
* If a complex type derives by restriction,
there is no requirement that Java properties representing the attributes
or elements removed by the restriction to be disabled. This is because
(as noted earlier), derivation by restriction is handled the same as
derivation by extension.
* When the complex type definition’s
_\{abstract}_ property is _false_ , a factory method is generated in the
package’s _ObjectFactory_ class introduced in
link:jaxb.html#a482[See Java Package].” The factory method
returns the type of the Java value class. The name of the factory method
is generated by concatenating the following components:
* The string constant _create_ .
* The _name_ of the Java value class.
The schema-derived Java value class is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation @XmlType, specified in Section
link:jaxb.html#a2578[See @XmlType]. The @XmlType annotation
elements are derived in terms of the abstract model properties for a
complex type definition summarized in link:jaxb.html#a4907[See
Complex Type Definition Schema Component] as follows:
=== [[a956]]Annotate Java value class with @XmlType element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlType element
|@XmlType value
|name |complex
type definition's \{name}
|namespace
|\{target namespace}
|propOrder a|
When \{content type} is element-only
\{content model} and top-level \{compositor} is xs:sequence, ordered
list of JAXB property names representing order of xs:elements in
\{content model}.
+
All other cases do not need to set propOrder.
|===
=== Example: Complex Type: Derivation by Extension
XML Schema Fragment (from XSD PART 0 primer):
<xs:complexType name="Address"> +
<xs:sequence> +
<xs:element name="name" type="xs:string"/> +
<xs:element name="street" type="xs:string"/> +
<xs:element name="city" type="xs:string"/> +
</xs:sequence> +
</xs:complexType>
<xs:complexType name="USAddress"> +
<xs:complexContent> +
<xs:extension base="ipo:Address"> +
<xs:sequence> +
<xs:element name="state" type="xs:string"/> +
<xs:element name="zip" type="xs:integer"/> +
</xs:sequence> +
</xs:extension> +
</xs:complexContent> +
</xs:complexType>
Default Java binding:
public class Address \{ +
String getName() \{...} +
void setName(String) \{...} +
String getStreet() \{...} +
void setStreet(String) \{...} +
void getCity() \{...} +
void setCity(String) \{...} +
}
+
import java.math.BigInteger;
public class USAdress extends Address \{ +
String getState() \{...} +
void setState(String) \{...}\{ +
BigInteger getZip() \{...} +
void setZip(BigInteger) \{...} +
} +
+
class ObjectFactory \{ +
Address createAddress() \{...} +
USAddress createUSAddress() \{...} +
}
=== [[a973]]Simple Content Binding
=== Binding to Property
By default, a complex type definition with
simple content is bound to a Java property defined by:
* _name:_ The property name must be “
_value_ ”.
* _base type, predicate, collection type:_
As specified in [XSD Part 1], when a complex type has simple content,
the content type (\{content type}) is always a simple type schema
component. And a simple type component always maps to a Java datatype
(link:jaxb.html#a702[See Simple Type Definition]”). Values of
the following three properties are copied from that Java type:
* base type
* predicate
* collection type
The schema-derived JAXB property representing
simple content is annotated, either explicitly or by default mapping
annotations, with the mapping annotation @XmlValue, specified in Section
link:jaxb.html#a3331[See @XmlValue].
=== Example: Simple Content: Binding To Property
XML Schema fragment:
<xs:complexType name="internationalPrice"> +
<xs:simpleContent> +
<xs:extension base="xs:decimal"> +
<xs:attribute name="currency" type="xs:string"/> +
</xs:extension> +
</xs:simpleContent> +
</xs:complexType>
Default Java binding:
class InternationalPrice \{ +
/** Java property for simple content */ +
@XmlValue +
java.math.BigDecimal getValue() \{...} +
void setValue(java.math.BigDecimal value) \{...} +
+
/** Java property for attribute*/ +
String getCurrency() \{...} +
void setCurrency(String) \{...} +
}
=== xsd:anyType
_xsd:anyType_ is the root of the type
definition hierarchy for a schema. All complex type definitions in a
schema implicitly derive from _xsd:anyType_ . Given that the JAXB 2.0
architecture does not define a common base class for all JAXB class
bindings of complex type definitions, the only possible binding property
base type binding for _xsd:anyType_ is to _java.lang.Object_ . This
binding enables all possible type and element substitutions for an
element of type _xsd:anyType_ .
=== Binding of element with type _xsd:anyType_
+
<xs:element name="anyContent/> <!-- _@type_ defaults to _xs:anyType_
--> +
<xs:complexType name="base"> +
<xs:sequence>
<xs:element ref="anyContent/> +
<xs:element name="anyContentAgain" type="xs:anyType"/> +
</xs:sequence> +
</xs:complexType> +
+
public class Base \{ +
void setAnyContent(Object obj); +
Object getAnyContent(); +
void setAnyContentAgain(Object obj); +
Object getAnyContentAgain(); +
}
A schema author defines an element to be of
type _xs:anyType_ to defer constraining an element to a particular type
to the xml document author. Through the use of _xsi:type_ attribute or
element substitution, an xml document author provides constraints for an
element defined as _xs:anyType_ . The JAXB unmarshaller is able to
unmarshal a schema defined _xsd:anyType_ element that has been
constrained within the xml document to an easy to access JAXB mapped
class. However, when the xml document does not constrain the
_xs:anyType_ element, JAXB unmarshals the unconstrained content to an
element node instance of a supported DOM API.
Type substitution is covered in more detail
in Section link:jaxb.html#a1148[See Type Substitution of a
Complex Type Definition] and link:jaxb.html#a1158[See Type
Substitution of a Simple Type Definition]. Element substitution is
covered in more detail in Section link:jaxb.html#a1223[See Bind
to a Simple Element property].
=== Attribute Group Definition
There is no default mapping for an attribute
group definition. When an attribute group is referenced, each attribute
in the attribute group definition becomes a part of the [attribute uses]
property of the referencing complex type definition. Each attribute is
mapped to a Java property as described in
link:jaxb.html#a1252[See Attribute use]“. If the attribute group
definition contains an attribute wildcard, denoted by the
_xs:anyAttribute_ element, then the referencing complex type definition
will contain a property providing access to wildcard attributes as
described in link:jaxb.html#a1306[See Attribute Wildcard]“.
=== [[a996]]Model Group Definition
When a named model group definition is
referenced, the JAXB property set representing its content model is
aggregated into the Java value class representing the complex type
definition that referenced the named model group definition as
illustrated in link:jaxb.html#a999[See Binding for a reference
to a model group definition.]”
image:xmlb-16.png[image]
=== [[a999]]Binding for a reference to a model group definition.
This binding style results in the same
properties occurring within both Java value class’s A and C to represent
the referenced Model Group B’s content model.
When a model group definition’s content model
contains an XML Schema component that is to be bound to a Java value
class, element class or enum type, it is desirable to only create a
single Java representation, not one for each complex content that
references the named model group definition. This default binding from a
model group definition’s content model is defined in
link:jaxb.html#a1012[See Deriving Class Names for Named Model
Group Descendants]."
To meet the JAXB 2.0 goal of predictable
unmarshalling of invalid XML content, the JAXB 1.0 customization for
binding a model group to a JAXB mapped class is no longer supported.
link:jaxb.html#a386[See Flexible Unmarshalling]“details the
rationale behind this change.
=== Bind to a set of properties
A non-repeating reference to a model group
definition, when the particle referencing the group has _\{max occurs}_
equal to one, results in a set of content properties being generated to
represent the content model. link:jaxb.html#a1332[See Content
Model - Particle, Model Group, Wildcard]” describes how a content model
is bound to a set of properties and has examples of the binding.
=== Bind to a list property
A reference to a model group definition from
a particle with a repeating occurrence is bound by default as specified
in link:jaxb.html#a1402[See Bind a repeating occurrence model
group]“.
=== Example:
Schema fragment contains a particle that
references the model group definition has a _\{maxOccurs}_ value greater
than one.
<xs:group name="AModelGroup"> +
<xs:choice> +
<xs:element name="A" type="xs:int"/> +
<xs:element name="B" type="xs:float"/> +
</xs:choice> +
</xs:group> +
+
<xs:complexType name="foo"> +
<xs:sequence> +
<xs:group ref="AModelGroup" maxOccurs="unbounded"/> +
<xs:element name="C" type="xs:float"/> +
</xs:sequence> +
</xs:complexType>
Derived Java representation:
public class Foo \{ +
/** A valid general content property of AModelGroup content +
model.*/ +
@XmlElements(\{@XmlElement(type=Integer.class, name="A"), +
@XmlElement(type=Float.class, name="B")}) +
java.util.List<Object> getAModelGroup() \{...} +
+
float getC() \{...} +
void setC(float value) \{...} +
};
=== [[a1012]]Deriving Class Names for Named Model Group Descendants
When a model group definition’s content model
contains XML Schema components that need to be bound to a Java class or
interface, this section describes how to derive the package and name for
the Java value class, enum type or element class derived from the
content model of the model group definition. The binding of XML Schema
components to Java classes/interfaces is only performed once when the
model group definition is processed, not each time the model group
definition is referenced as is done for the property set of the model
group definition.
XML Schema components occurring within a
model group definition’s content model that are specified by this
chapter and the customization chapter to be bound to a Java value class,
interface or typesafe enum class are bound as specified with the
following naming exceptions:
* _package_ : The element class, Java value
class or typesafe enum class is bound in the Java package that
represents the target namespace containing the model group definition.
* _name_ : The name of the interface or
class is generated as previously specified with one additional step to
promote uniqueness between interfaces/classes promoted from a model
group definition to be bound to a top-level class within a Java package.
By default, a prefix for the interface/class name is computed from the
model group definition’s _\{name}_ using the XML name to Java identifier
algorithm.If the schema customization _[jaxb:globalBindings]_ @
_localScoping_ has a value of _toplevel_ , then a prefix is not
generated from the model group definition’s _\{name}_ .
For example, given a model group definition
named _Foo_ containing an element declaration named _bar_ with an
anonymous complex type definition, the anonymous complex type definition
is bound to a Java value class with the name _FooBar_ . The following
figure illustrates this example.
image:xmlb-17.png[image]
=== Default binding for anonymous type def within a model group definition.
Note that even customization specified Java
value class, interface or typesafe enum class names are prepended with
the model group definition’s name. Thus, if a model group definition
named _Foo_ contains an anonymous simple type definition with a typesafe
enum class customization name of _Colors,_ the enum type name is
_FooColors_ .
=== Attribute Declaration
An attribute declaration is bound to a Java
property when it is referenced or declared, as described in
link:jaxb.html#a1252[See Attribute use],” from a complex type
definition.
=== [[a1023]]Element Declaration
This section describes the binding of an XML
element declaration to a Java representation. For a description of how
this binding has changed since the previous version, see
link:jaxb.html#a680[See Java Element Representation Summary]“.
This section introduces why a JAXB technology user has to use instances
of JAXB element as opposed to instances of Java datatypes or Java value
class when manipulating XML content.
An XML element declaration is composed of the
following key components:
* its qualified name is \{target namespace}
and \{name}
* its value is an instance of the Java class
binding of its \{type definition}
* whether the element’s content is
_\{nillable}_
Typically, an instance of
_jakarta.xml.bind.JAXBElement<T>_ , returned by an element factory method,
__ represents an element declaration’s key components. An instance of a
Java value class or content interface represents only the value of an
element. Commonly in JAXB binding, the Java representation of XML
content enables one to manipulate just the value of an XML element, not
an actual element instance. The binding compiler statically associates
the XML element qualified name to a content property and this
information is used at unmarshal/marshal time. For cases where the
element name can be dynamically altered at runtime, the JAXB user needs
to manipulate elements, not element values. The following schema/derived
Java code example illustrates this point.
=== Example:
Given the XML Schema fragment:
<xs:complexType name="chair_kind"> +
<xs:sequence> +
<xs:element name="has_arm_rest" type="xs:boolean"/> +
</xs:sequence> +
</xs:complexType> +
Schema-derived Java value class:
public class ChairKind \{ +
boolean isHasArmRest() \{...} +
void setHasArmRest(boolean value) \{...} +
}
A user of the Java value class _ChairKind_
never has to create a Java instance that both has the value of local
element _has_arm_rest_ and knows that its XML element name is
_has_arm_rest_ . The user only provides the value of the element to the
content-property _hasArmRest_ . A JAXB implementation associates the
content-property _hasArmRest_ with XML element name _has_arm_rest_ when
marshalling an instance of _ChairKind_ .
The next schema/derived Java code example
illustrates when XML element information can not be inferred by the
derived Java representation of the XML content. Note that this example
relies on binding described in link:jaxb.html#a1384[See Bind
wildcard schema component].”
=== Example:
<xs:complexType name="chair_kind"> +
<xs:sequence> +
<xs:any/> +
</xs:sequence> +
</xs:complexType> +
+
public class ChairKind \{ +
@XmlAnyElement(lax="true") +
java.lang.Object getAny() \{...} +
void setAny(java.lang.Object elementOrValue) \{...} +
}
For this example, the user can provide an
Element instance to the _any_ content-property that contains both the
value of an XML element and the XML element name since the XML element
name could not be statically associated with the content-property _any_
when the Java representation was derived from its XML Schema
representation. The XML element information is dynamically provided by
the application for this case. link:jaxb.html#a1332[See Content
Model - Particle, Model Group, Wildcard] cover additional circumstances
when one can use JAXB elements.
=== [[a1040]]Bind to _JAXBElement<T>_ Instance
The characteristics of the generated
ObjectFactory element factory method that returns an _JAXBElement<T>_
instance are derived in terms of the properties of the
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
* The element factory method is generated
into the _ObjectFactory_ class in the Java package that represents the
binding of the element declaration’s \{target namespace}.
* The element factory method returns an
instance of _jakarta.xml.bind.JAXBElement<T>_ , where _T_ is the Java
value class representing the _\{type definition}_ of the element
declaration. The factory method sets the element name of the returned
instance to the element declaration’s fully qualified name.
* The element factory method has a single
parameter that is an instance of type _T_ , where T is the Java value
class representing the _\{type definition}_ of the element declaration.
* The name of the factory method is generated
by concatenating the following components:
* The string constant _create_ .
* By default, if the element declaration is
nested within another XML Schema component, then the concatenation of
all outer Java class names representing those XML Schema components. If
the schema customization _[jaxb:globalBindings]_ @ _localScoping_ has a
value of toplevel, skip this step.
* A name that is generated from the element
declaration’s _\{name}_ using the XML Name to Java identifier name
mapping algorithm specified in link:jaxb.html#a4656[See The Name
to Identifier Mapping Algorithm].
* The _JAXBElement<T>_ property for nil __
test whether an element’s content model is _xsi:nil="true"_ .
For example, an element declaration named
_Foo_ __ with a type of __ _xs:int_ __ that is nested within the content
model of complex type definition _Bar_ would have the following factory
method generated in the containing Java package’s _ObjectFactory_ class:
JAXBElement<Integer> createBarFoo(Integer
value) \{...}
Default binding rules require an element
declaration to be bound to element factory method under the following
conditions:
* All non-abstract, named element
declarations with global \{scope} are bound to an element factory method
that returns an _JAXBElement<T>_ instance. The rationale is that any
global element declaration can occur within a wildcard context and one
might want to provide element instances, not instances of the element’s
type, the element’s value, for this case.
* All local element declarations, having a
\{scope} of a complex type definition, occurring within content that is
mapped to a general content property of JAXB elements must have an
element factory method generated. General content property is specified
in link:jaxb.html#a1344[See General content property]” An
example of when a content model is mapped to a general content property,
forcing the generation of element declarations is at
link:jaxb.html#a1359[See Examples].”
The schema-derived element factory method is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation _@XmlElementDecl_ , specified in Section 8. The
_@XmlElementDecl_ annotation elements are derived in terms of the
abstract model properties for an element declaration summarized in
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
=== Annotate element instance factory with @XmlElementDecl element-value pairs.
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlElementDecl element
|@XmlElementDecl value
|name |element
declaration’s _\{name}_
|namespace |
_\{target namespace}_
|scope |If
_\{scope}_ is _global_ , _JAXBElement.GlobalScope.class_ . else the JAXB
Java value class representing the _\{scope}_ ing complex type
definition.
|substitutionHeadName
|If optional _\{substitution group
affiliation}_ exists, its local name.
|substitutionHeadNamespace
|If optional _\{substitution group
affiliation}_ exists, its namespace.
|===
The element declaration’s _\{type}_ can
result in additional JAXB annotations being generated on the element
instance factory. For more details, see link:jaxb.html#a820[See
Annotations for standard XML datatypes]“and @XmlList in
link:jaxb.html#a883[See List]“.
The schema-derived ObjectFactory class
containing the @XmlElementDecl annotations is annotated with
@XmlRegistry annotation.
=== [[a1068]]Bind to Element Class
link:jaxb.html#a1698[See <class>
Declaration]“customization enables the binding of an element declaration
with a named type definition to a schema-derived Element class. The
characteristics of the schema-derived Element class are derived in terms
of the properties of the link:jaxb.html#a4937[See Element
Declaration Schema Component] as follows:
* The name of the generated Java Element
class is derived from the element declaration \{name} using the XML Name
to Java identifier mapping algorithm for class names.
* Each generated Element class must extend
the Java value class _jakarta.xml.bind.JAXBElement_ <T>. The next bullet
specifies the schema-derived Java class name to use for generic
parameter _T_ .
* If the element declaration’s \{type
definition} is
* Anonymous
Generic parameter _T_ from the second bullet
is set to the schema-derived class represented the anonymous type
definition generated as specified in Section 6.7.3.
* Named
Generic parameter T from the second bullet is
set to the Java class representing the element declaration’s \{type
definition}.
The _ObjectFactory_ method to create an
instance of name has a single parameter that is an instance of type _T_
. By default, the name of the ObjectFactory method is derived by
concatenating outerClassNames and name. When schema customization,
_[jaxb:globalBindings]_ _@localScoping,_ specified in Section
_link:jaxb.html#a1582[See Usage],_ has a value of _toplevel_ ,
then the outer Classnames are ommitted from the factory method name.
* If \{scope} is
* _Global:_ The derived Element class is
generated into the Java package that represents the binding of \{target
namespace}.
* _A Complex Type Definition:_ By default,
the derived Element class is generated within the Java value class
represented by the complex type definition value of \{scope}. When
_@localScoping_ is _toplevel_ , the derived element class is generated
as a toplevel class.
* The property for nil __ test whether
element’s content model is _xsi:nil="true"_ .
* Optional \{value constraint} property with
pair of _default_ or _fixed_ and a value. +
If a default or fixed value is specified, the data binding system must
substitute the default or fixed value if an empty tag for the element
declaration occurs in the XML content.
A global binding customization,
_@generateElementClass,_ specified in link:jaxb.html#a1580[See
<globalBindings> Declaration]“enables this binding over the default
binding specified in the previous subsection.
=== [[a1084]]Binding of an anonymous complex type definition
An anonymous complex type definition is bound
to a generated schema-derived Java value class by default.
The naming characteristics of the generated
Java value class is derived in terms of the properties of the
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
* The name of the generated Java value class
is derived from the element declaration \{name} using the XML Name to
Java identifier
* The _package_ of the generated Java value
class is the same as the package derived from the element declaration’s
_\{target namespace}_ .
* The _outer class names_ of the generated
Java value class is determined by the element declaration’s _\{scope}._
If _\{scope}_ is:
* Global +
There is no outer class name.
* A Complex Type Definition +
By default, the derived Java value class is generated nested within the
Java value class represented by the complex type definition value of
\{scope}. The derived Java value is not generated nested when schema
customization _[globalBindings]_ has attribute _@localScoping_ with a
value of _toplevel_ _._
* _base class:_ Same as defined in
link:jaxb.html#a933[See Java value class]“.
* _property set:_ As defined in
link:jaxb.html#a933[See Java value class]“.
* A type factory method is generated in the
package’s _ObjectFactory_ class introduced in
link:jaxb.html#a482[See Java Package].” The factory method
returns the type of the Java value class. The name of the factory method
is generated by concatenating the following components:
* The string constant _create_ .
* If the element declaration containing the
anonymous complex type definition is nested within another complex type
definition representing a value class and [globalBindings] @localScoping
has a value of _nested_ , then the concatenation of all outer Java class
names. This step is skipped when @localScoping has a value of _toplevel_
.
* The _name_ of the Java value class.
The schema-derived value class is annotated
with the mapping annotation _@XmlType_ , specified in Section
link:jaxb.html#a2578[See @XmlType]. The _@XmlType_ annotation
elements are set as described in link:jaxb.html#a956[See
Annotate Java value class with @XmlType element-value pairs] with one
exception: _@XmlType.name()_ is set to the empty string.
As long as the element declaration is not one
of the exception cases specified in link:jaxb.html#a1113[See
Bind Element Declaration to JAXBElement]", the schema-derived value
class is annotated with the mapping annotation _@XmlRootElement_
specified in Section 8. The _@XmlRootElement_ annotation elements are
derived in terms of the abstract model properties for the referenced
global element declaration summarized in
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
=== Annotate JAXB Mapped Class with @XmlRootElement element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlRootElement element
|@XmlRootElement value
|namespace a|
When element declaration _\{target
namespace}_ is absent, +
(i.e. unqualified local element declaration), @XmlElement.namespace() is
not set. +
Otherwise, set @XmlElement.namespace() to
value of _\{target namespace}_ . (either a qualified local element
declaration or a reference to a global element)
Note: same result could be achieved with
package level annotation of @XmlSchema and not setting
@XmlElement.namespace.
|name |element
declaration _\{name}_
|===
=== Example:
Given XML Schema fragment:
<xs:element name="foo"> +
<xs:complexType> +
<xs:sequence> +
<xs:element name="bar" type="xs:int"/> +
</xs:sequence> +
</xs:complexType> +
</xs:element>
Derived Java code:
/*Value class representing element
declaration with an anonymous complex type definition.*/ +
@XmlType(name="") +
@XmlRootElement(namespace="", name="foo") +
public class Foo \{ +
int getBar() \{...} +
void setBar(int value) \{...} +
}; +
=== [[a1113]]Bind Element Declaration to JAXBElement
An element declaration with an anonymous
complex type definition is not bound to a _@XmlRootElement_ ,annotated
schema-derived class when the element declaration is:
* nillable
* the head element or a member of a
substitution group
* non-global (i.e. declared within a complex
type definition)
When one or more of the above conditions are
met, the schema-derived class representing the anonymous complex type
definition must not be annotated with _@XmlRootElement_ . Instead, an
element factory that returns _JAXBElement<_ _anonymousTypeValueClass_
_>_ may be generated as specified in link:jaxb.html#a1040[See
Bind to JAXBElement<T> Instance]“.
=== Example:
Given XML Schema fragment:
+
<xs:element name="foo" nillable="true"> +
<xs:complexType> +
<xs:sequence> +
<xs:element name="bar" type="xs:int"/> +
</xs:sequence> +
</xs:complexType> +
</xs:element> +
Derived Java code:
/*Value class representing anonymous complex
type definition.*/ +
@XmlType(name="") +
public class Foo \{ +
int getBar() \{...} +
void setBar(int value) \{...} +
}; +
@XmlRegistry +
class ObjectFactory \{ +
// type factory method +
Foo createFoo() \{...} +
// element factory method +
@XmlElementDecl(name="foo", namespace="", nillable="true") +
JAXBElement<Foo> createFoo(Foo value) \{...} +
}
=== Bind to a Property
A local element declaration is bound by
default to a Java property as described in
link:jaxb.html#a541[See Properties]. The characteristics of the
Java property are derived in terms of the properties of the
link:jaxb.html#a4937[See Element Declaration Schema Component]
and link:jaxb.html#a5022[See Particle Schema Component] as
follows:
* The name of the Java property is derived
from the \{element declaration} property’s \{name} property using the
XML Name to Java Identifier mapping algorithm described in
link:jaxb.html#a4656[See The Name to Identifier Mapping
Algorithm].
* A _base type_ for the Java property is
derived from the _\{element declaration}_ property’s _\{type
definition}_ property as described in binding of Simple Type Definition
in _link:jaxb.html#a702[See Simple Type Definition]_ .” or
link:jaxb.html#a917[See Complex Type Definition]". If the base
type is initially a primitive type and this JAXB property is _optional_
, the _[jaxb:globalBinding]_ customization _@optionalProperty_ controls
the binding of an optional primitive property as described in
link:jaxb.html#a1582[See Usage]“.
* An optional _predicate_ for the Java
property is constructed from the _\{element declaration}_ property’s
_\{type definition}_ property as described in the binding of simple type
definition to a Java representation.
* An optional _collection type_ for the Java
property is derived from:
* _\{element declaration}_ property’s
_\{type definition}_ property as described in the binding of simple type
definition to a Java representation
* the \{particle} property’s \{max occurs}
value being greater than one.
* Element defaulting +
The default value is derived from the element declaration’s \{value
constraint} property’s value. Unlike attribute defaulting, an element
only defaults when there is an empty element tag in an xml document. The
element’s default value is captured by mapping annotation
_@XmlElement.defaultValue()_ . The unmarshaller sets the property to
this default value when it encounters an empty element tag. The
marshaller can output an empty element tag whenever the element’s
_@XmlValue_ property value is the same as its defaulted value..
* A local element declaration that binds to a
JAXB property with a primitive base type is bound as an _optional_ JAXB
property if the element declaration is a member of a choice model group
or the element declaration’s particle has optional occurrence, \{ _min
occurs} value is "0",_ or belongs to a model group that has optional
occurrence. By default, the optional JAXB property binds the property’s
base type to the Java wrapper class for the primitive type. One can test
and set the absence of an optional property using null. The
_[jaxb:globalBinding]_ customization _@optionalProperty_ controls
alternative bindings of an optional primitive property as described in
link:jaxb.html#a1582[See Usage]“.
* If the element declaration’s \{nillable}
property is _“true”_ , the base type for the Java property is mapped to
the corresponding Java wrapper class for the Java primitive type.
Setting the property to the _null_ value indicates that the property has
been set to the XML Schema concept of @xs: _nil=’true_ ’.
This Java property is a member of the Java
value class that represents the binding of the complex type definition
containing the local element declaration or reference to global element.
The schema-derived JAXB property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotation _@XmlElement_ , specified in
Section 8, “@XmlElement”. The _@XmlElement_ annotation elements are
derived in terms of the abstract model properties for the referenced
global element declaration summarized in
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
=== Annotate JAXB Property with @XmlElement element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlElement element
|@XmlElement value
|namespace a|
When element declaration _\{target
namespace}_ is absent, +
(i.e. unqualified local element declaration), @XmlElement.namespace() is
not set. +
Otherwise, set @XmlElement.namespace() to
value of _\{target namespace}_ . (either a qualified local element
declaration or a reference to a global element)
Note: same result could be achieved with
package level annotation of @XmlSchema and not setting
@XmlElement.namespace.
|name |element
declaration _\{name}_
|nillable |element
declaration _\{nillable}_
|defaultValue |if
element declaration _\{value constraint}_ is not absent, set
defaultValue() to _\{value constraint}_ ’s value.
|===
link:jaxb.html#a1240[See Xml Schema
example containing an element substitution group]illustrates how to
define an element substitution group and to reference the head element
of the substitution group within an Xml Schema.
link:jaxb.html#a1242[See avo binding of Xml Schema from CODE
EXAMPLE 6-5] illustrates the Java bindings of the element substation
enabled schema. link:jaxb.html#a1244[See Element substitution
using Java bindings from CODE EXAMPLE 6-6] demonstrates element
substitution using the JAXB API.link:jaxb.html#a1246[See Invalid
element substitution using Java bindings from CODE EXAMPLE 6-6]
illustrates invalid element substitution handling.
=== [[a1148]]Type Substitution of a Complex Type Definition
link:jaxb.html#a917[See Complex Type
Definition]“describes that when a complex type definition is mapped to
Java value class that the type definition derivation hierarchy is
preserved in the Java class hierarchy. This preservation makes it quite
natural for Java to support the Xml Schema mechanism type substitution
across all complex type definitions.
Performing an invalid type substitution is
not detected as a fail-fast check when setting the JAXB property or
checked as part of marshalling the element declaration. Invalid type
substitution can be checked by optional validation that can be enabled
as part of unmarshalling or marshalling process.
The following three code examples illustrate
how type substitution is supported in JAXB 2.0 for a complex type
definition hierarchy.
=== [[a1152]]Xml Schema example containing type derivation hierarchy
+
<xs:schema targetNamespace="travel:acme" xmlns:a="travel:acme"> +
+
<!-- Define type definition derivation hierarchy --> +
<xs:complexType name=" _TransportType_ ">...<\xs:complexType> +
<xs:complexType name=" _PlaneType_ "> +
<xs:extension base="a:TransportType">...<\xs:complexType> +
<xs:complexType name=" _AutoType_ "> +
<xs:extension base="a:TransportType">...<\xs:complexType> +
<<xs:complexType name=" _SUV_ "> +
<xs:extension base="a:AutoType">...<\xs:complexType> +
+
<xs:complexType name=" _itinerary_ "> +
<xs:sequence> +
<!-- Type substitution possible for " _transport"._ -->. +
<xs:element name=" _transport_ " type=" _TransportType_ "/> +
</xs:sequence> +
</xs:complexType> +
</xs:schema> +
=== [[a1154]]Java binding of Xml Schema from link:jaxb.html#a1240[See Xml Schema example containing an element substitution group]
package travel.acme; +
+
// Type derivation hierarchy from schema is preserved in Java binding. +
public class _TransportType_ \{ ... } +
public class _PlaneType_ extends TransportType \{ ... } +
public class _AutoType_ extends TransportType \{ ... } +
public class _SUV_ extends AutoType \{ ... } +
+
public class ObjectFactory \{ +
// Type Factories +
TransportType createTransportType()\{...} +
AutoType createAutoType()\{...} +
PlaneType createPlaneType()\{...} +
TrainType createSUV()\{...} +
} +
+
public class Itinerary \{ +
// Simple property supports type substitution. +
_TransportType_ getTransport()\{...} +
void setTransport( _TransportType_ value) +
}
=== Type substitution using Java bindings from link:jaxb.html#a1242[See avo binding of Xml Schema from CODE EXAMPLE 6-5]
+
ObjectFactory of = ...; +
Itinerary itinerary = of.createItinerary(); +
itinerary.setTransport(of.createTransportType); // Typical Use +
+
// Type Substitution +
// transport marshalled as <e:transport xsi:type="e:AutoType">> +
itinerary.setTransport(of.createAutoType()); +
+
// transport marshalled as <e:transport xsi:type="e:PlaneType">> +
itinerary.setTransport(of.createPlaneType());
=== [[a1158]]Type Substitution of a Simple Type Definition
An XML element declaration having a simple
type definition is bound most naturally to a JAXB property with a base
type that is a primitive Java datatype. Unfortunately, this strongly
typed binding conflicts with fully supporting type substitution of a
simple type definition. Unlike the JAXB binding of complex type
definitions, the simple type derivation hierarchy is not preserved when
binding builtin XML Schema simple type definitions to corresponding Java
datatypes as specified in link:jaxb.html#a715[See Atomic
Datatype]“. Since there is not a natural Java inheritance hierarchy to
support simple type substitution, a JAXB property customization is
required to enable optimal support of simple type substitution.
For example, the most natural binding of an
XML Schema built-in datatype _xs:int_ is to the Java primitive datatype,
_int_ . However, simple type substitution implies that an _xs:short_ or
a complex type definition that derives by extension from _xs:int_ can be
type substituted for an _xs:int_ within an XML document using the
_xsi:type_ attribute. The strongly typed JAXB property with Java type
_int_ would never allow for a Java value class for the complex type to
be assigned to a JAXB property of type _int_ .
By default, unmarshalling handles simple type
substitution by assigning the relevant part of the type substituted
content to the JAXB property. When the value of the xsi:type attribute
resolves to:
* a type that derives by restriction from the
element’s schema type. +
The substituted value is always parsable into a legal value of the base
type of the JAXB property being type substituted.
* a complex type that derives by extension
from element’s schema type. +
The JAXB binding of the substituted complex type definition must have
one JAXB property annotated with an _@XmlValue_ that is assignable to
the type substituted JAXB property’s base type. Attribute(s) associated
with the complex type definition can not be preserved by the default
binding.
The rationale behind the default binding is
that substitution of a simple type definition occurs rarely. The default
JAXB binding is more convenient and precise for programmer to use. Its
one drawback is that it does not faithfully preserve _xsi:type_
occurring in an XML document.
To enable more comprehensive support of
simple type substituting of an XML element with a simple type
definition, the JAXB property customization specified in
link:jaxb.html#a1809[See Generalize/Specialize baseType with
attribute @name]“enables setting the property’s base type to the more
general type of _java.lang.Object._ This binding allows for retention of
the XML document _xsi:type_ and attributes associated with complex type
definition substituted for an XML element with a simple type definition.
When an _xsi:type_ value refers to a type definition not registered with
_JAXBContext_ instance, the content is unmarshalled as the element’s
schema type.
To preserve an application-defined simple
type definition involved in simple type substitution, it must be mapped
to a JAXB mapped class as described in link:jaxb.html#a803[See
Bind to a JAXB mapped class]“. This can be achieved for all simple type
definitions in a schema using the customization _<jaxb:globalBinding
mapSimpleTypeDefs="true"/>_ or it can be achieved per simple type
definition using <jaxb:class> customization. An invalid simple type
substitution can be detected by JAXP 1.3 validation enabled at unmarshal
or marshal time
Below are examples of the type substitution
of an XML element’s simple type definition for the default and
customized binding.
=== [[a1168]]Schema fragment to illustrate simple type substitution
<xsd:element name="Price"> +
<xsd:complexType> +
<xsd:sequence> +
<xsd:element name="name" type="xsd:string"/> +
_<!-- element price subject to type substitution-> +
_ <xsd:element name="price" type="xsd:int"/> +
</xsd:sequence> +
</xsd:complexType> +
</xsd:element> +
<xsd:complexType name="AmountType"> +
<xsd:simpleContent> _<!-- type substitutable for xs:int --> +
_ <xsd:extension base="xsd:int"> +
<xsd:attribute name="currency" type="xsd:string"/> +
</xsd:extension> +
</xsd:simpleContent> +
</xsd:complexType> +
<xsd:simpleType name="AppInt"> +
<xsd:restriction base="xsd:int"/> +
</xsd:simpleType>
=== [[a1170]]XML documents with simple type substitution
<product> +
<name>hotdog</name><price>3</price> +
</product>
<product> +
<name>peanuts</name> +
<price _xsi:type="short_ ">4</price> +
</product>
<product> +
<name>popcorn</name> +
<price _xsi:type="AppInt_ ">5</price> +
</product>
<product> +
<name>sushi</name> +
<price _xsi:type="AmountType"_ currency="yen">500</price> +
</product>
=== Default Handling of Simple Type Substitution
=== [[a1176]]Default JAXB binding of link:jaxb.html#a1168[See Schema fragment to illustrate simple type substitution]
public class AmountType \{ +
@XmlValue +
int getValue()\{...} void setValue(int value) \{...} +
String getCurrency() \{...} void setCurrency(String value) \{...} +
} +
@XmlRootElement(namespace="", name="product") +
public class Product \{ +
int getPrice()\{...} void setPrice(int value) \{ ...} +
int getName() \{...} void setName(String value) \{...} +
}
Unmarshalling XML document fragments from
link:jaxb.html#a1170[See XML documents with simple type
substitution] into link:jaxb.html#a1176[See Default JAXB binding
of CODE EXAMPLE 6-1] JAXB binding of element _product_ results in the
_xsi:type_ and attributes associated with JAXB mapped class _Price_
being lost as part of the unmarshal process. This loss is illustrated by
comparing link:jaxb.html#a1179[See Product instances from
unmarshalling XML docs from CODE EXAMPLE 6-2] with
link:jaxb.html#a1204[See Product instances from unmarshalling
XML docs from CODE EXAMPLE 6-2].
=== [[a1179]]Product instances from unmarshalling XML docs from link:jaxb.html#a1170[See XML documents with simple type substitution]
[width="100%",cols="20%,20%,20%,20%,20%",options="header",]
|===
|document xsi:type
| _Product.name +
value_ | _Product.price +
value_ | _Product.price +
type_ | _marshal Product.price xsi:type_
| |hotdog
|3 |int
|
|xs:short |peanuts
|4 |int
|
|AppInt |popcorn
|5 |int
|
|AmountType |sushi
|500 |int
|
|===
=== Simple Type Substitution enabled by JAXB customizations.
The simple type definition _AppInt_ is mapped
to a JAXB class either by _<jaxb:class>_ customization or by
_<jaxb:globalBindings mapSimpleTypeDef="true"/>_ . The JAXB property
_Product.Price_ is mapped to a JAXB property with a general base type of
_java.lang.Object_ with following external JAXB schema customization:
<jaxb:bindings
schemaLocation="link:jaxb.html#a1168[See Schema fragment to
illustrate simple type substitution]" +
node="//xsd:element[@name=’price’]"> +
<jaxb:property> +
<jaxb:baseType name="java.lang.Object"/> +
</jaxb:property> +
</jaxb:bindings>
specified in link:jaxb.html#a1809[See
Generalize/Specialize baseType with attribute @name]“.
=== [[a1201]]Customized JAXB binding of link:jaxb.html#a1168[See Schema fragment to illustrate simple type substitution]
public class AmountType \{ +
@XmlValue +
int getValue()\{...} void setValue(int value) \{...} +
String getCurrency() \{...} void setCurrency(String value) \{...} +
} +
public class AppInt \{ +
@XmlValue +
int getValue() \{...} void setValue(int value) \{...} +
} +
public class Product \{ +
// enable simple type substitution with base type of Object +
@XmlElement(type=java.lang.Integer.class) +
Object getPrice()\{...} void setPrice(Object value) \{ ...} +
int getName() \{...} void setName(String value) \{...} +
}
Unmarshalling XML document fragments from
link:jaxb.html#a1170[See XML documents with simple type
substitution] into link:jaxb.html#a1201[See Customized JAXB
binding of CODE EXAMPLE 6-1] JAXB binding of element _product_ preserves
the _xsi:type_ and attributes associated with JAXB mapped class
_AmountType_ is illustrated in link:jaxb.html#a1204[See Product
instances from unmarshalling XML docs from CODE EXAMPLE 6-2].
=== [[a1204]]Product instances from unmarshalling XML docs from link:jaxb.html#a1170[See XML documents with simple type substitution]
[width="100%",cols="20%,20%,20%,20%,20%",options="header",]
|===
|document xsi:type
| _Product.name +
value_ | _Product. +
price +
value_ | _Product. +
price +
Java type_ | _Marshal +
Product. +
price +
_ _xsi:type_
| |hotdog
|3 |Integer
|
|xs:short |peanuts
|4 |Short
|xs:short
|AppInt |popcorn
|5 |AppInt
|AppInt
|AmountType |sushi
|\{value=500, +
currency=”yen”} |AmountType
|AmountType
|===
=== [[a1223]]Bind to a Simple Element property
Element substitution group is an Xml Schema
mechanism that enables the substitution of one named element for
another. This section uses terms and concepts described in Section 4.6
of [XSD Part 0] and normatively defined in Section 2.2.2.2 of [XSD Part
1].
The following constraints assist in defining
the Java binding that enables element substitution group:
. Element substitution is only possible for a
reference to a global element.
. Assuming the absence of the Xml Schema
constraints on substitution, any global element can be made the head
element of a substitution group.
. All elements in a substitution group must
derive from or have the same type definition as the head element.
{empty}To support element substitution, for
each global element reference to a head element of a substitution group
or to an abstract element, it is necessary to generate the Element
property bindings defined in link:jaxb.html#a630[See Element
Property].link:#a5373[22] This property enables the overriding
of the schema-specified element name bound to a JAXB property by setting
and getting the JAXB element representation,
_jakarta.xml.bind.JAXBElement<T>_ . The name property of the JAXBElement
_<T>_ instance overrides the schema specified element declaration name.
To enable the passing of any element that could be part of the element
substitution group, it is necessary to accept any JAXBElement derivation
that extends Java binding of the head element’s type definition. Using
the upper bounded wildcard notation for a generic JAXBElement container,
_JAXBElement<? extends T>_ , the element property is able to get and set
any element that has an element value that is a subtype of T. Compile
time checking will not allow invalid JAXBElement derivations to be
passed to the Element property setter. When the element type is correct
but the element name is not part of the substitution group, this invalid
scenario can only be caught at runtime by validation or optional
fail-fast checking by the element property
setter.link:#a5374[23]
The schema-derived Element property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotation _@XmlElementRef_ , specified in
Section 8.10.3, “@XmlElementRef”. The _@XmlElementRef_ annotation
elements are derived in terms of the abstract model properties for the
referenced global element declaration summarized in
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
=== Annotate Element Property with @XmlElementRef element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlElementRef element
|@XmlElementRef value
|value
|jakarta.xml.bind.JAXBElement.class
|namespace
|referenced element declaration _\{target
namespace}_
|name |referenced
element declaration _\{name}_
|===
link:jaxb.html#a1240[See Xml Schema
example containing an element substitution group]illustrates how to
define an element substitution group and to reference the head element
of the substitution group within an Xml Schema.
link:jaxb.html#a1242[See avo binding of Xml Schema from CODE
EXAMPLE 6-5] illustrates the Java bindings of the element substation
enabled schema. link:jaxb.html#a1244[See Element substitution
using Java bindings from CODE EXAMPLE 6-6] demonstrates element
substitution using the JAXB API.link:jaxb.html#a1246[See Invalid
element substitution using Java bindings from CODE EXAMPLE 6-6]
illustrates invalid element substitution handling.
=== [[a1240]]Xml Schema example containing an element substitution group
<xs:schema targetNamespace="travel:acme"
xmlns:a="travel:acme"> +
+
<!-- See type definition derivation hierarchy defined in
link:jaxb.html#a1152[See Xml Schema example containing type
derivation hierarchy]for +
complexType definitions TransportType, PlaneType, AutoType and SUV.--> +
< +
<!-- Define element substitution group. a:transport is head
element.--> +
<xs:element name="transport" type="a:TransportType"/> +
<xs:element name="plane" type="a:PlaneType"
substitutionGroup="a:transport"/> +
<xs:element name="auto" type="a:AutoType"
substitutionGroup="a:transport"/><!- +
+
<xs:complexType name="itinerary"> +
<xs:sequence> +
<!-- Global element reference. +
References head element of element substitution group. --> +
<xs:element ref="a:transport"/> +
</xs:sequence> +
</xs:complexType> +
<\xs:schema>
=== [[a1242]]avo binding of Xml Schema from link:jaxb.html#a1240[See Xml Schema example containing an element substitution group]
ppackage travel.acme; +
public class ObjectFactory \{ +
// Type Factories +
TransportType createTransportType(); +
AutoType createAutoType(); +
PlaneType createPlaneType(); +
TrainType createSUVType(); +
+
// Element Instance Factories +
JAXBElement<AutoType> createAuto(AutoType value); +
JAXBElement<PlaneType> createPlane(PlaneType value); +
JAXBElement<TransportType> createTrain(TransportType value); +
} +
+
// See Java binding of type derivation hierarchy in
link:jaxb.html#a1154[See Java binding of Xml Schema from CODE
EXAMPLE 6-5] +
+
public class Itinerary \{ +
// Element substitution supported by link:jaxb.html#a630[See
Element Property]" +
JAXBElement<? extends TransportType> getTransport(); +
void setTransport(JAXBElement<? extends TransportType> value); +
}
=== [[a1244]]Element substitution using Java bindings from link:jaxb.html#a1242[See avo binding of Xml Schema from CODE EXAMPLE 6-5]
+
ObjectFactory of = ...; +
Itinerary itinerary = of.createItinerary(); +
itinerary.setTransport(of.createTransportType()); // Typical use. +
+
// Element substitution: +
// Substitute <e:auto> for schema specified <e:transport>. +
itinerary.setTransport(of.createAuto(of.createAutoType())); +
+
// Substitute <e:plane> for schema specified <e:transport>> +
itinerary.setTransport(of.createPlane(of.createPlaneType())); +
+
// Combination of element and type substitution: +
_// Substitutes <e:auto xsi:type="e:SUV"> for <e:transport>> +
_ itinerary.setTransport(of.createAuto(of.createSUV()));
=== [[a1246]]Invalid element substitution using Java bindings from link:jaxb.html#a1242[See avo binding of Xml Schema from CODE EXAMPLE 6-5]
+
<!-- Add elements not part of element substitution group. --> +
<xs:element name="apple" type="xsd:string"/> +
<xs:complexType name="spaceShuttle"> +
<xs:extension base="a:TransportType">...<\xs:complexType> +
<xs:element name="spaceShuttle" type="a:spaceShuttleType"> +
+
ObjectFactory of = ...; +
Itinerary itinerary = of.createItinerary(); +
// Invalid element substitution +
// compile time error: method not found +
//Element apple of type JAXBElement<String> does not match +
//bounded wildcard JAXBElement<? extends TransportType>. +
itinerary.setTransport(of.createApple("granny smith")); +
+
//Invalid element substitution detected by validation. +
// Element spaceShuttle not part of substitution group. +
// Adding _substitutionGroup="transport"_ to line 4 fixes this. +
itinerary.setTranport( +
of.createSpaceShuttle(of.createSpaceShuttleType()));
=== Bind to an Element Collection property
A repeating occurrence element declaration
that is element substitutable binds solely to a JAXB Collection property
of JAXBElement.
=== Bind repeating occurrence element substitution variant of link:jaxb.html#a1240[See Xml Schema example containing an element substitution group]
<!--deleted schema that remains same --> +
<xs:complexType name="itinerary"> +
<xs:sequence> +
<!-- Repeating occurance to substitutable global element reference.
--> +
<xs:element ref="a:transport" _maxOccurs="unbounded"_ /> +
</xs:sequence> +
</xs:complexType> +
<\xs:schema> +
+
Java Binding: +
public class Itinerary \{ +
List<JAXBElement<? extends TransportType>> getTransport(); +
}
=== [[a1252]]Attribute use
A ‘required’ or ‘optional’ attribute use is
bound by default to a Java property as described in
link:jaxb.html#a541[See Properties]. The characteristics of the
Java property are derived in terms of the properties of the
link:jaxb.html#a5012[See Attribute Use Schema Component] and
link:jaxb.html#a4965[See Attribute Declaration Schema Component]
as follows:
* The name of the Java property is derived
from the \{attribute declaration} property’s \{name} property using the
XML Name to Java Identifier mapping algorithm described in
link:jaxb.html#a4656[See The Name to Identifier Mapping
Algorithm].
* A _base type_ for the Java property is
derived from the _\{attribute declaration}_ property’s _\{type
definition}_ property as described in binding of Simple Type Definition
in _link:jaxb.html#a702[See Simple Type Definition]_ .”. If the
base type is initially a primitive type and this JAXB property is
_optional_ , the _[jaxb:globalBinding]_ customization
_@optionalProperty_ controls the binding of an optional primitive
property as described in link:jaxb.html#a1582[See Usage]“.
* An optional _predicate_ for the Java
property is constructed from the _\{attribute declaration}_ property’s
_\{type definition}_ property as described in the binding of simple type
definition to a Java representation.
* An optional _collection type_ for the Java
property is derived from the _\{attribute declaration}_ property’s
_\{type definition}_ property as described in the binding of simple type
definition to a Java representation.
* The _default value_ for the Java property
is the value from the attribute use’s \{value constraint} property. If
the optional \{value constraint} is absent, the default value for the
Java property is the Java default value for the base type.
* The JAXB property is _optional_ when the
attribute use’s _\{required}_ property is _false_ .
This Java property is a member of the Java
value class that represents the binding of the complex type definition
containing the attribute use
The JAXB property getter for this attribute
is annotated, either explicitly or via default mapping, with the mapping
annotation @XmlAttribute, specified in Section
link:jaxb.html#a3230[See @XmlAttribute]. The @XmlAttribute
element values are derived in terms of the properties of the
link:jaxb.html#a5012[See Attribute Use Schema Component] and
link:jaxb.html#a4965[See Attribute Declaration Schema Component]
as follows:
=== [[a1262]]Annotate Attribute property getter method with @XmlAttribute annotation
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlAttribute element
|@XmlAttribute value
|name |attribute
declaration's \{name}
|namespace a|
if attribute declaration’s \{target
namespace} absent, set to “”
otherwise, set to \{target namespace}
|required
|attribute use's \{required}
|===
*
=== Example:
Given XML Schema fragment:
<xs:complexType name="USAddress"> +
<xs:attribute name="country" type="xs:string"/> +
</xs:complexType>
Default derived Java code:
public class USAddress \{ +
@XmlAttribute(name="country", targetNamespace="", +
required="false"); +
public String getCountry() \{...} +
public void setCountry(String value) \{...} +
}
=== [[a1277]]Bind to a Java Constant property
Rather than binding to a read/write JAXB
property, an attribute use with a _fixed_ \{value constraint} property
can be bound to a Java Constant property. This mapping is not performed
by default since _fixed_ is only a validation constraint. The user must
set the binding declaration attribute _fixedAttributeToConstantProperty_
on _<jaxb:globalBinding>_ element as specified in
link:jaxb.html#a1582[See Usage] or on _<jaxb:property>_ element
as specified in link:jaxb.html#a1786[See Usage] to enable this
mapping.
=== Example:
Given XML Schema fragment:
<xs:annotation><xs:appinfo>
<jaxb:globalBindings
fixedAttributeAsConstantProperty="true"/>
</xs:appinfo></xs:annotation> +
<xs:complexType name="USAddress"> +
<xs:attribute name="country" type="xs:NMTOKEN" fixed="US"/> +
</xs:complexType>
If the appropriate binding schema
customization enables mapping a fixed XML value to Java constant
property, the following Java code fragment is generated.
public class USAddress \{ +
@XmlAttribute +
public static final String COUNTRY="US"; +
... +
}
The schema-derived constant for this fixed
attribute is annotated, either explicitly or via default mapping, with
the mapping annotation _@XmlAttribute._ The elements of _@XmlAttribute_
are set as described in _link:jaxb.html#a1262[See Annotate
Attribute property getter method with @XmlAttribute annotation]_
Note that if derivation by restriction
constrains an existing attribute declaration to be fixed, this
refinement must not be bound to a constant property. The initial binding
of the attribute to a JAXB property remains the only binding of the
attribute in the Java class hierarchy.
=== Contributions to Local Structural Constraint
If the attribute use’s \{required} property
is true, the local structural constraint for an instance of the Java
value class requires that the corresponding Java property to be set when
the Java value class instance is validated.
=== [[a1290]]Binding an IDREF component to a Java property
An element or attribute with a type of
_xs:IDREF_ refers to the element in the instance document that has an
attribute with a type of _xs:ID_ or derived from type _xs:ID_ with the
same value as the _xs:IDREF_ value. Rather than expose the Java
programmer to this XML Schema concept, the default binding of an
_xs:IDREF_ component maps it to a Java property with a base type of
_java.lang.Object_ . The caller of the property setter method must be
sure that its parameter is identifiable. An object is considered
identifiable if one of its properties is derived from an element or
attribute that is or derives from type _xs:ID_ . The JAXB mapped class
must have one property annotated with an @XmlID program annotation as it
is specified in Section 8. There is an expectation that all instances
provided as values for properties’ representing an _xs:IDREF_ should
have the Java property representing the _xs:ID_ of the instances set
before the content tree containing both the _xs:ID_ and _xs:IDREF_ is
marshalled. If a property representing an _xs:IDREF_ is set with an
object that does not have its _xs:ID_ set, the _NotIdentifiableEvent_ is
reported by marshalling.
* The name of the Java property is derived
from the \{name} property of the attribute or element using the XML Name
to Java Identifier mapping algorithm described in
link:jaxb.html#a4656[See The Name to Identifier Mapping
Algorithm].
* A _base type_ for the Java property is
java.lang.Object.
* There is no _predicate_ for a property
representing an _xs:IDREF_ .
* An optional _collection type_
* Default and fixed values can not be
supported for an attribute with type _xs:IDREF_ .
The schema-derived JAXB property representing
xs:IDREF(s) is annotated, either explicitly or by default mapping
annotations, with the mapping annotation @XmlIDREF, specified in Section
8.
=== Example:
Given XML Schema fragment:
<xs:complexType name="Book"> +
<xs:sequence> +
_<xs:element name="author" type="xs:IDREF"/> +
_ <!-- ... --> +
</xs:sequence> +
</xs:complexType> +
<xs:complexType name="AuthorBio"> +
<xs:sequence><!-- ... --> </xs:sequence> +
_<xs:attribute name="name" type="xs:ID"/> +
_ </xs:complexType>
Schema-derived Java value class:
public class Book \{ +
@XmlIDREF +
java.lang.Object getAuthor() \{...} +
+
/** Parameter referencedObj should have an attribute or +
* child element with base type of xs:ID by validation +
* or marshal time. +
*/ +
void setAuthor(java.lang.Object referencedObj)\{...} +
} +
public class AuthorBio\{ +
@XmlID +
String getName()\{...} +
void setName(String value)\{...} +
}
Demonstration of a Java content instance
referencing another instance:
Book book = ...; +
AuthorBio authorBio = ...; +
book.setAuthor(authorBio); +
authorBio.setName("<some author’s name>"); +
// The content instance root used to validate or marshal book must +
// also include "authorBio" as a child element somewhere. +
// A Java content instance is not included
Note that _ID_ and _IDREF_ mechanisms do not
incorporate type definitions that can be referenced. To generate
stronger typing for a JAXB property representing an IDREF, the schema
customization described in link:jaxb.html#a1809[See
Generalize/Specialize baseType with attribute @name]" can be used to
specialize the binding.. link:jaxb.html#a1820[See Specialize
binding of an IDREF via customization] illustrates the generation of
stronger typing for the above example.
=== [[a1306]]Attribute Wildcard
Attribute wildcard is an extensibility
feature in XML Schema. It enables an XML document author to introduce
attribute(s) to an element that were not statically associated with the
element’s complex type definition. Obviously, it is not possible to bind
such an attribute to a strongly typed JAXB property as the previous
section describes for attribute use schema component. The JAXB binding
of a complex type definition that contains an attribute wildcard,
directly or indirectly, provides dynamic access to the wildcard
attributes via the following property:
// Return, by reference, a mapping of
attribute QName and String. +
Map<QName, String> getOtherAttributes();
The returned attribute map provides dynamic
access to wildcard attributes associated with a complex type definition.
The key to the map is the attribute’s QName and the key’s value is the
String value of the attribute.
The schema-derived property getter method is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation _@XmlAnyAttribute_ , specified in Section 8.
The following code examples show the JAXB
binding for xs:anyAttribute and how to manipulate wildcard attributes
using this binding.
=== Bind anyAttribute to a JAXB property
+
<xs:schema targetNamespace="http://a.org"> +
<xs:complexType name=" _widget_ "> +
<xs:anyAttribute/> +
<xs:attribute name="color" type="xs:string"/> +
</xs:complexType> +
</xs:schema> +
+
package org.a; +
import javax.xml.namespace.QName; +
import java.util.Map; +
public class _Widget_ \{ +
String getColor()\{...} +
void setColor(String value)\{...} +
@XmlAnyAttribute Map<QName, String> _getOtherAttributes_ ()\{...} +
}
=== Dynamic access to wildcard attribute and attribute use
+
import jakarta.xml.bind.DatatypeConverter; +
Widget w = ...; +
Map attrs = w.getOtherAttributes(); +
+
// access schema-defined global attribute associated with +
// complexType defintion widget via attribute wildcard. +
QName IS_OPEN=new QName("http://example.org", "isOpen"); +
boolean isOpen = DatatypeConverter.parseBoolean(attrs.get(IS_OPEN)); +
+
// set wildcard attribute value +
attrs.put(IS_OPEN, DatatypeConverter.printBoolean(false)); +
+
// semantically the same results setting attribute use via +
// dynamic or static setter for attribute use. +
attrs.put(new QName("color"), "red"); +
+
// iterate over wildcard attributes +
for (Map.Entry<QName,String> e: attrs.entrySet()) \{ +
System.out.println("Attribute: " + e.getKey() + +
" Value:" + e.getValue()); +
}
=== [[a1316]]Redefine
Redefinition allows an existing XML Schema
component to be “renamed” and its new definition takes the place of the
old one. The binding of the redefined schema components, simple and
complex type definitions and model and attribute group declarations, are
described in the following subsections.
=== Bind Redefined Simple Type Definition
As introduced in
link:jaxb.html#a702[See Simple Type Definition]“, a schema
component using a simple type definition typically binds to a JAXB
property. The base type, collection type and predicate of the JAXB
property are derived from the simple type definition. Thus, the redefine
of a simple type definition results in the redefinition of the simple
type definition being used to derive the base type, collection type and
predicate of the JAXB property.
The one exception to this binding is that a
simple type definition with enum facets is sometimes bound to an enum
type. A redefined simple type definition that binds to an enum type, as
described in link:jaxb.html#a829[See Enum Type]“, is not bound
to a Java representation, only the redefinition is bound to an enum
type.
=== Bind Redefined Complex Type Definition
A redefinition of a type definition must use
the original type definition as its base type definition. The redefined
complex type definition is bound to a Java value class or interface name
that prepends “_” to the class name. The redefinition complex type
definition is bound to a class that extends the JAXB class that
represents the redefined complex type definition.
=== Binding of a redefined complex type definition
File: v1.xsd: +
<!-- Extracted from Section 4.2.2 of [XSD1] --> +
<xs:complexType name="personName"> +
<xs:sequence> +
<xs:element name="title" type="xs:string" minOccurs="0"/> +
<xs:element name="forename" type="xs:string" +
minOccurs="0" maxOccurs="unbounded"/> +
</xs:sequence> +
</xs:complexType>
File: v2.xsd: +
<xs:redefine schemaLocation="v1.xsd"> +
<xs:complexType name="personName"> +
<xs:complexContent> +
<xs:extension base="personName"> +
<xs:sequence> +
<xs:element name="generation" minOccurs="0"/> +
</xs:sequence> +
</xs:extension> +
</xs:complexContent> +
</xs:complexType> +
</xs:redefine>
Java binding: +
// binding of file v1.xsd complex type definition for personName +
@XmlType(name="_PersonName") +
public class _PersonName \{ +
void setTitle(String value); String getTitle(); +
List<String> getForename(); +
} +
// binding of v2.xsd redefinition for complex type personName +
@XmlType(name="PersonName") +
public class PersonName extends _PersonName \{ +
void setGeneration(Object value); Object getGeneration(); +
=== Bind Redefined Group Definition
The attribute or model group redefinition is
used instead of the initial group definition to construct the property
set of the content model(s) that reference the redefined attribute or
model group definition. The construction of a property set is described
in link:jaxb.html#a933[See Java value class]“.
Since there is no binding of an attribute or
model group definition to a Java representation, no other special case
handling is required for this binding.
=== Identity Constraint
An identity constraint does not represent any
data, it represents a constraint that is enforced by validation. These
constraints can be checked by optional validation that can be enabled at
either unmarshal and/or marshal time.
=== [[a1332]]Content Model - Particle, Model Group, Wildcard
This section describes the possible Java
bindings for the content model of a complex type definition schema
component with a \{content type} property of _mixed_ or _element-only_ .
The possible element content(s) and the valid ordering between those
contents are constrained by the \{particles} describing the complex type
definition’s content model. The Java binding of a content model is
realized by the derivation of one or more content-properties to
represent the element content constrained by the model group. Section
6.12.1 through 6.12.7 describes the _element binding_ of a content
model.
=== Element binding style
The ideal Java binding would be to map each
uniquely named element declaration occurring within a content model to a
single JAXB property. The model group schema component constraint,
element declarations consistent, specified in [XSD-Part 1] ensures that
all element declarations/references having the same \{target namespace}
and \{name} must have the same top-level type definition. This model
allows the JAXB technology user to specify only the content and the JAXB
implementation infers the valid ordering between the element content
based on the \{particles} constraints in the source schema. However,
there do exist numerous scenarios that this ideal binding is not
possible for parts of the content model or potentially the entire
content model. For these cases, default binding has a fallback position
of representing the element content and the ordering between the content
using a _general content model_ . The scenarios where one must fallback
to the general content model will be identified later in this
subsection.
=== Bind each element declaration name to a JAXB property
This approach relies on the fact that a model
group merely provide constraints on the ordering between children
elements and the user merely wishes to provide the content. It is
easiest to introduce this concept without allowing for repeating
occurrences of model groups within a content model. Conceptually, this
approach presents all element declarations within a content model as a
set of element declaration \{name}’s. Each one of the \{name}’s is
mapped to a content-property. Based on the element content that is set
by the JAXB application via setting content-properties, the JAXB
implementation can compute the order between the element content using
the following methods.
Computing the ordering between element
content within [children] of an element information item
* Schema constrained fixed ordering or
semantically insignificant ordering
The sequence in the schema represents an
ordering between children elements that is completely fixed by the
schema. Schema-constrained ordering is not exposed to the Java
programmer when mapping each element in the sequence to a Java property.
However, it is necessary for the marshal/unmarshal process to know the
ordering. No new ordering constraints between children elements can be
introduced by an XML document or Java application for this case.
Additionally, the Java application does not need to know the ordering
between children elements. When the compositor is _all_ , the ordering
between element content is not specified semantically and any ordering
is okay. So this additional case can be handled the same way.
* Schema only constrains content and does not
significantly constrain ordering
If the ordering between the children elements
is significant and must be accessible to the Java application, then the
ordering is naturally preserved in Java representation via a collection.
Below are examples where schema provides very little help in
constraining order based on content.
<xs:choice maxOccurs="unbounded"> ...
</xs:choice> +
<xs:sequence maxOccurs="unbounded"> ... </xs:sequence>
=== [[a1344]]General content property
A general content property is, as its name
implies, the most general of all content properties. Such a property can
be used with any content specification, no matter how complex. A general
content property is represented as a List property as introduced in
link:jaxb.html#a595[See List Property]. Unlike the prior
approach where the JAXB implementation must infer ordering between the
element content, this approach always requires the JAXB technology user
to specify a valid ordering of element and text content. This approach
has the benefit of providing the application with more control over
setting and knowing the order between element content.
A general content property is capable of
representing both element information items and character data items
occurring within [children] of an element information item. Character
data is inserted into the list as java.lang.String values. Element data
is added to the list as instances of JAXB element. To support wildcard
content occurring as part of a general content property, xml data
content with no static Java binding is added and accessed from the list
as instances of _org.w3c.org.dom.Node_ .
The schema-derived Collection property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotations reflecting what content is
within the Collection.
* If the content model is mixed, the property
is annotated as _@XmlMixed_ . See link:jaxb.html#a1369[See Bind
mixed content]“for details.
* link:jaxb.html#a1351[See Collection
of Element types]“describes an optimized binding of a collection of
element values, instead of a collection of JAXB elements annotated with
_@XmlElementRefs(@XmlElementRef, ...)_ .
* If optimized binding can not be used, each
element in the content model is represented by an _@XmlElementRef_ ,
described in link:jaxb.html#a1223[See Bind to a Simple Element
property]“. If there is more than one element annotations needed, they
must occur as elements in the map annotation _@XmlElementRefs_ specified
in Section 8.10.3, “@XmlElementRef”.
=== [[a1351]]Collection of Element types
If the content model for a general content
property meets all of the following constraints, the collection can be
optimized to be a list of value classes instead of a list of JAXB
elements.
* If the content model is not mixed and does
not contain a wildcard.
* If none of the element declarations in the
content model are abstract or the head of an element substitution group.
* If none of the element declarations in the
content model have a xml datatype that is or derives from xs:list or
xs:IDREF.
* For all element declarations in the content
model, there does not exist two distinct element declarations whose
types bind to the same Java datatype.
* If not more than one element declaration in
the content model is nillable.
Such a collection is annotated with @
_XmlElements_ annotation, specified in Section 8, that contains a
_@XmlElement_ annotation for each unique Java datatype within the
collection. The _@XmlElement_ annotation associates an element name with
each unique Java datatype in the collection
=== [[a1359]]Examples
=== Example 1: Complex content model of Elements with primitive types
<xs:complexType name="Base"> +
<xs:choice maxOccurs="unbounded"> +
<xs:element name="A" type="xs:string"/> +
<xs:element name="B" type="xs:string"/> +
<xs:element name="C" type="xs:int"/> +
</xs:choice> +
</xs:complexType> +
public class ObjectFactory \{ +
// Element instance factories. +
JAXBElement<String> createBaseA(String value)\{...} +
JAXBElement<String> createBaseB(String value)\{...} +
JAXBElement<Integer> createBaseC(Integer value)\{...} +
// Type factories +
Base createBase()\{...} +
} +
public class Base \{ +
+
/** +
* A general content list that can contain +
* element instances representing A, B and/or C. +
*/ +
@XmlElementRefs(\{ @XmlElementRef(name="A", value=JAXBElement.class), +
@XmlElementRef(name="B", value=JAXBElement.class), +
@XmlElementRef(name="C", value=JAXBElement.class)}) +
List<JAXBElement> getAOrBOrC()\{...} +
}
=== Example 2: Optimized Binding to a Collection of Element Types
XML Schema fragment:
<xs:complexType name="AType"/> +
<xs:complexType name="BType"/> +
<xs:complexType name="FooBar"> +
<xs:choice maxOccurs="unbounded"> +
<xs:element name="foo" type="AType"/> +
<xs:element name="bar" type="BType"/> +
</xs:choice> +
</xs:complexType>
Default derived Java code:
public class AType \{ ... } +
public class BType \{ ... } +
+
class ObjectFactory \{
// element instance factories only +
JAXBElement<AType> createFooBarFoo(AType value); +
JAXBElement<BType> createFooBarBar(BType value); +
} +
+
public class FooBar \{
/** +
‘* Collection of element types: AType and BType. */ +
@XmlElements(\{@XmlElement(value=AType.class, name="Foo"), +
@XmlElement(value=BType.class, name="Bar")}) +
List<Object> getFooOrBar() \{...} +
};
=== [[a1369]]Bind mixed content
When a complex type definition’s _\{content
type}_ is “mixed,” its character and element information content is
bound to general content list as described in
link:jaxb.html#a1344[See General content property].” Character
information data is inserted as instances of _java.lang.String_ into a
JAXB collection property.
The schema-derived Collection property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotation _@XmlMixed_ , specified in
Section 8.
=== Example:
Schema fragment loosely derived from mixed
content example from +
[XSD Part 0].
<xs:element name="letterBody"> +
<xs:complexType mixed="true"> +
<xs:sequence> +
<xs:element name="name" type="xs:string"/> +
<xs:element name="quantity" type="xs:positiveInteger"/> +
<xs:element name="productName" type="xs:string"/> +
<!-- etc. --> +
</xs:sequence> +
</xs:complexType> +
</xs:element>
Derived Java code:
import java.math.BigInteger; +
class ObjectFactory \{
// element instance factories only +
JAXBElement<LetterBody> createLetterBody(LetterBody value); +
JAXBElement<String> createLetterBodyName(String value); +
JAXBElement<BigInteger> +
createLetterBodyQuantity(BigInteger value); +
JAXBElement<String> +
createLetterBodyProductName(String value); +
} +
public class LetterBody implements JAXBElement<LetterBody> \{ +
+
/** Mixed content can contain instances of Element classes +
Name, Quantity and ProductName. Text data is represented as +
java.util.String for text. +
*/ +
@XmlMixed +
@XmlElementRefs(\{ +
@XmlElementRef(name="productName", type=JAXBElement.class), +
@XmlElementRef(name="quantity", type=JAXBElement.class), +
@XmlElementRef(name="name", type=JAXBElement.class)}) +
List getContent()\{...} +
}
The following instance document
<letterBody> +
Dear Mr.<name>Robert Smith</name> +
Your order of <quantity>1</quantity> <productName>Baby +
Monitor</productName> shipped from our warehouse. .... +
</letterBody>
could be constructed using JAXB API.
LetterBody lb =
ObjectFactory.createLetterBody(null); +
List gcl = lb.getContent(); +
gcl.add("Dear Mr."); +
gcl.add(ObjectFactory.createLetterBodyName("Robert Smith")); +
gcl.add("Your order of "); +
gcl.add(ObjectFactory.
createLetterBodyQuantity(new
BigInteger("1"))); +
gcl.add(ObjectFactory.createLetterBodyProductName("Baby Monitor")); +
gcl.add("shipped from our warehouse");
Note that if any element instance is placed
into the general content list, _gcl_ , that is not an instance of
_LetterBody.Name_ , _LetterBody.Quantity_ or _LetterBody.ProductName_ ,
validation would detect the invalid content model. With the fail fast
customization enabled, element instances of the wrong type are detected
when being added to the general content list, _gcl_ .
=== Bind wildcard schema component[[a1384]]
A wildcard is mapped to a simple
content-property with:
* Content-property name set to the constant “
_any_ ”. A binding schema customization could provide a more
semantically meaningful content-property name.
* Content-property base type set to
_java.lang.Object_ by default.
Wildcard content is represented as one of the
following:
. JAXB element +
Either an instance of _jakarta.xml.bind.JAXBElement<T>_ or a JAXB class
annotated with _@XmlRootElement. +
_ Corresponds to a recognized global element tag name registered with
the instance _jakarta.xml.bind.JAXBContext_ , meaning the schema(s)
describing the element content is registered with the _JAXBContext_
instance, see link:jaxb.html#a298[See JAXBContext] on how
bindings are registered with a _JAXBContext_ instance.,
. instance of _jakarta.xml.bind.JAXBElement. +
_ Corresponds to an unknown element name but a recognized type
definition specified by _@xsi:type_ on the element. JAXBElement
_declaredType_ is set to _java.lang.Object_ since the unknown element
declaration’s default type is _xs:anyType_ .
. element node instance of a supported xml
infoset API +
Necessary to represent Xml data content that does not have a schema
defined element or type definition. Such content is allowed by element
_xs:any_ with attribute _@processContents=”lax”_ or _"skip"_ .
. See content-property predicate for a
wildcard.
. If the _maxOccurs_ is greater than one, the
content property is mapped to a collection property. The default
collection property is a List property of base type java.lang.Object.
. These is no default value.
Since the schema does not contain any
information about the element content of a wildcard content, even the
content-property, by default, can not infer an XML element tag for
wildcard element content.
The schema-derived property getter method for
representing wildcard content is annotated, either explicitly or by
default mapping annotations, with the mapping annotation
_@XmlAnyElement_ , specified in Section 8. The @XmlAnyElement annotation
element values are derived in terms of the abstract model properties for
wildcard summarized in link:jaxb.html#a5032[See Wildcard Schema
Component] as follows:
=== Annotate JAXB property with @XmlAnyElement element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlAnyElement element
|@XmlAnyElement element value
|lax |If wildcard
schema component’s _\{process contents}_ is _lax_ or _strict_ , +
set _@XmlAnyElement.lax()_ to _true_ . +
+
else if _\{process contents}_ is _skip_ , set _@XmlAnyElement.lax()_ to
_false_ .
|value |
_jakarta.xml.bind.annotation. +
W3CDomHandler.class_
|===
=== [[a1402]]Bind a repeating occurrence model group
A choice or sequence model group, containing
more than one member, with a repeating occurrence, _maxOccurs_ attribute
greater than one, is bound to a general content property in the
following manner:
* Content-property name is derived in
following ways:
* If a named model group definition is being
referenced, the value of its \{name} property is mapped to a Java
identifier for a method using the algorithm specified in
link:jaxb.html#a4656[See The Name to Identifier Mapping
Algorithm].
* To derive a content property name for
unnamed model group, see link:jaxb.html#a4780[See Deriving an
identifier for a model group].
* Content-property base type set to
_java.lang.Object_ . A binding schema customization could provide a more
specialized java class.
* Content-property predicate validates the
order between element instances in the list and whether the occurrence
constraints for each element instance type is valid according to the
schema.
* Since the _maxOccurs_ is always greater
than one, the content property is mapped to a collection property. The
default collection property is a List property.
* These is no default value.
The schema-derived collection property is
annotated as specified in link:jaxb.html#a1344[See General
content property]“and link:jaxb.html#a1351[See Collection of
Element types]“.
=== Local structural Constraints
The list content property’s value must
satisfy the content specification of the model group. The ordering and
element contents must satisfy the constraints specified by the model
group.
=== [[a1414]]Content Model Default Binding
The following rules define _element_ binding
style for a complex type definition’s content model.
. If \{content type} is mixed, bind the
entire content model to a general content property with the
content-property name “ _content_ ”. See
link:jaxb.html#a1369[See Bind mixed content]” for more details.
. If (1) a particle has \{max occurs} >1 and
(2) its \{term} is a model group and (3) all the particles in the model
group have \{terms} that bind to different Java datatypes, bind to a
collection of element types. See complete list of constraints required
to perform this optimized binding in link:jaxb.html#a1351[See
Collection of Element types]“.
. If (1) a particle has \{max occurs} >1 and
(2) its \{term} is a model group, then that particle and its descendants
are mapped to one general content property that represents them. See
link:jaxb.html#a1402[See Bind a repeating occurrence model
group]” for details.
. Process all the remaining particles (1)
whose \{term} are wildcard particles and (2) that did not belong to a
repeating occurrence model group bound in step. 2. If there is only one
wildcard, bind it as specified in link:jaxb.html#a1384[See Bind
wildcard schema component].” If there is more than one, then fallback to
representing the entire content model as a single general content
property. See link:jaxb.html#a1344[See General content
property]).
. Process all particles (1) whose \{term} are
element declarations and (2) that do not belong to a repeating
occurrence model group bound in step.2.
First, we say a particle has a label L if it
refers to an element declaration whose \{name} is L. Then, for all the
possible pair of particles P and P’ in this set, if the following
constraints are not met:
. If P and P’ have the same label, then they
must refer to the same element declaration.
. If P and P’ refer to the same element
reference, then its closest common ancestor particle may not have
sequence as its \{term}.
If either of the above constraints are
violated, it is not possible to map each element declaration to a unique
content property. Fallback to representing the entire content model as a
single general content property.
Otherwise, create a content property for each
label L as follows:
* The content property name is derived from
label name L.
* The base type will be the Java type to
which the referenced element declaration maps.
* The content property predicate reflects the
occurrence constraint.
* The content property collection type
defaults to ‘ _list_ ’ if there exist a particle with label L that has
\{maxOccurs} > 1.
* For the default value, if all particles
with label L has a \{term} with the same \{value constraint} default or
fixed value, then this value. Otherwise none.
Below is an example demonstrating of not
meeting the uniqueness constraints of 5(a) and 5(b) specified above.
+
<xs:sequence> +
<xs:choice> +
<xs:element ref="ns1:bar"/> (A) +
<xs:element ref="ns2:bar"/> (B) +
</xs:choice> +
<xs:element ref="ns1:bar"/> (C) +
</xs:sequence>
The pair (A,B) violates the first clause
because they both have the label “bar” but they refer to different
element declarations. The pair (A,C) violates the second clause because
their nearest common ancestor particle is the outermost _<sequence>_ .
This model group fragment is bound to a general content property.
=== Default binding of content model “derived by extension”
If a content-property naming collision occurs
between a content-property that exists in an base complex type
definition and a content-property introduced by a “derive by extension”
derived complex type definition, the content-properties from the
colliding property on are represented by a general content property with
the default property name _rest_ .
=== Example: +
derivation by extension content model with a content-property collision.
Given XML Schema fragment:
<xs:complexType name="Base"> +
<xs:sequence> +
<xs:element name="A" type="xs:int"/> +
<xs:element name="B" type="xs:int"/> +
</xs:sequence> +
</xs:complexType> +
+
<xs:complexType name="Derived"> +
<xs:complexContent> +
<xs:extension base="Base"> +
<xs:sequence> +
<xs:element name="A" type="xs:int"/> +
</xs:sequence> +
</xs:extension>
</xs:complexContent> +
</xs:complexType>
Default binding derived Java code:
public class Base \{ +
int getA()\{...} void setA(int)\{...} +
int getB()\{...} void setB(int)\{...} +
} +
+
public class Derived extends Base \{ +
/** +
* Instances of Derived.A must be placed in this general +
* content propert that represents the rest of the content +
* model. link:#a5375[24] */ +
List getRest()\{...} +
} +
class ObjectFactory \{ +
// element instance factories only +
JAXBElement<Integer> createDerivedA(Integer value)\{...} +
}
=== [[a1442]]Bind single occurrence choice group to a choice content property
Setting the _choiceContentProperty_ attribute
of _<jaxb:globalBindings>_ as specified in
link:jaxb.html#a1582[See Usage] enables this customized binding
option.
A non-repeating choice model group is bound
to a simple property. The simple choice content property is derived from
a choice model group as follows:
* The choice content property name is either
the referenced model group definition _\{name}_ or obtained using the
algorithm specified in link:jaxb.html#a4780[See Deriving an
identifier for a model group].
* The choice content property _base type_ is
the first common supertype of all items within the choice model group,
with _java.lang.Object_ always being a common root for all Java
objects.link:#a5376[25]
* The predicate
* The collection type defaults to List if one
or more items in the choice model group bind to List.
* No default value.
A choice property consists of the following
methods:
* The _getChoiceID_ method returns the set
value. If the property has no set value then the value _null_ is
returned. Note that a set value of a primitive Java type is returned as
an instance of the corresponding Java wrapper class.
* The _setChoiceID_ method has a single
parameter that is the type of the choice content property _base type_ .
The _globalBindings_ and property
customization attribute, _choiceContentProperty,_ enables this
customized binding _._ The customization is specified in
link:jaxb.html#a1580[See <globalBindings> Declaration].”
=== Example:
XML Schema representation of a choice model
group.
<xs:choice> +
<xs:element name="foo" type="xs:int"/> +
<xs:element name="bar" type="xs:string"/> +
</xs:choice>
Derived choice content property method
signatures:
void setFooOrBar(Object)\{...} +
Object getFooOrBar()\{...}
=== [[a1459]]Modifying Schema-Derived Code
There exist a number of use cases on why a
developer would find it beneficial to modify schema-derived classes.
Here are some of those use cases.
* Add functionality to schema-derived
classes. +
Since schema-derived classes are derived from a data description
language, the derived classes only represent data and have no
object-level functionality.
* Add polymorphic methods to Java class
hierarchy generated from XML Schema type definition derivation
hierarchy.
* Initialize a JAXB property or field
representing an XML element with a default value. Regretfully, XML
Schema element defaulting is insufficient to accomplish this. Note that
XML Schema attribute defaulting is sufficient and does not require this
approach.
The JAXB 2.0 schema-derived class was
designed to be easily understandable and modifiable by a developer. For
many development environments, it is not sufficient to only run the
schema compiler once due to modification of the schema-derived classes.
Since schemas evolve over time, it is desirable to have the ability to
regenerate schema-derived classes from an updated schema while
preserving modification made by a developer. Given the complexities of
supporting this capability, a JAXB implementation is not required to
support regeneration from a schema into previously modified
schema-derived classes. External tools, such as an IDE, could assist in
supporting the sophisticated task of regeneration of a modified
schema-derived class in the future. To enable tools to support
regeneration, a JAXB implementation is required to have an option for
generating an annotation that enables a portable means for
distinguishing between developer code and generated code in a
schema-derived class.The next section describes the portable format for
distinguishing between generated and developer added/modified methods
and /or fields in a schema-derived class.
=== Distinguish between generated and user added code
A schema compiler must have an option to
generate the Common Annotation, _@javax.annotation.Generated_
annotation, specified in [CA], on every generated class, method and
field. If a developer does modify an _@Generated_ annotated method or
field, they must denote this modification by deleting the _@Generated_
annotation. If a developer adds a new method or field, it will not have
an _@Generated_ annotation on it. Based on these conventions, a JAXB
implementation in conjunction with an IDE or other external tool, would
be able to support regeneration of schema-derived code while preserving
developer additions/modifications to methods and fields in a
schema-derived class.
When schema compiler option to generate
_@Generated_ annotation is selected, the table describes the annotation
to be generated.
=== Annotate generated class, field and property with @Generated element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@Generated element
|@Generated element value
|value |fully
qualified class name of schema compiler
|date |date of
generation of schema-derived class. Value must follow the ISO 8601
standard.
|comment
|optional. Is implementation specific.
|===
=== Default Binding Rule Summary
Note that this summary is non-normative and
all default binding rules specified previously in the chapter take
precedence over this summary.
* Bind the following to Java package:
* XML Namespace URI
* Bind the following XML Schema components to
Java value class:
* Named complex type
* Bind to typesafe enum class:
* A named simple type definition with a
basetype that derives from “ _xs:NCName_ ” and has enumeration facets.
* Bind the following XML Schema components to
an element instance factory that returns _jakarta.xml.bind.JAXBElement<T>_
* A global element declaration with a named
type definition.
* Local element declaration with a named type
definition that can be inserted into a general content list.
* Bind the following XML Schema components to
a Java Element class
* A global element declaration with anonymous
type definition to a Java value class.
* Local element declaration with anonymous
type definition that can be inserted into a general content list.
* Bind to Java property
* Attribute use
* Particle with a term that is an element
reference or local element declaration.
Additionally, generate an element property
for an element reference to the head element of a substitution group.
* Bind to JAXB property: +
_getOtherAttributes(): java.util.Map<QName, String>_
* Attribute Wildcard occurring directly or
indirectly via an attribute group reference in a complex type
definition.
* Bind model group and wildcard content with
a repeating occurrence and complex type definitions with _mixed_
\{content type} to:
* A general content property - a List
content-property that holds Java instances representing element
information items and character data items. To support dynamic Xml
content that validates against xs:any processContents=”lax” or “skip”,
allow instances of org.w3c.dom.Node into the list.
== CHAPTER 7 -
[[a1498]]Customizing XML Schema to
Java Representation Binding
The default binding of source schema
components to derived Java representation by a binding compiler
sometimes may not meet the requirements of a JAXB application. In such
cases, the default binding can be customized using a binding
declaration. Binding declarations are specified by a _binding language_
, the syntax and semantics of which are defined in this chapter.
All JAXB implementations are required to
provide customization support specified here unless explicitly stated as
optional.
=== Binding Language
The binding language is an XML based language
which defines constructs referred to as binding declarations. A binding
declaration can be used to customize the default binding between an XML
schema component and its Java representation.
http://java.sun.com./xml/ns/jaxb[The schema
for binding declarations is defined in the namespace]
_http://java.sun.com/xml/ns/jaxb_ . This specification uses the
namespace prefix “ _jaxb_ ” to refer to the namespace of binding
declarations. For example,
<jaxb: binding declaration>
A binding compiler interprets the binding
declaration relative to the source schema and a set of default bindings
for that schema. Therefore a source schema need not contain a binding
declarations for every schema component. This makes the job of a JAXB
application developer easier.
There are two ways to associate a binding
declaration with a schema element:
* as part of the source schema (inline
annotated schema)
* external to the source schema in an
external binding declaration.
The syntax and semantics of the binding
declaration is the same regardless of which of the above two methods is
used for customization.
A binding declaration itself does not
identify the schema component to which it applies. A schema component
can be identified in several ways:
* explicitly - e.g. QName, XPath expressions
etc.
* implicitly - based on the context in which
the declaration occurs.
It is this separation which allows the
binding declaration syntax to be shared between inline annotated schema
and the external binding.
=== Extending the Binding Language
In recognition that there will exist a need
for additional binding declarations than those currently specified in
this specification, a formal mechanism is introduced so all JAXB
processors are able to identify _extension binding declarations_ . An
extension binding declaration is not specified in the _jaxb:_ namespace,
is implementation specific and its use will impact portability.
Therefore, binding customization that must be portable between JAXB
implementations should not rely on particular customization extensions
being available.
The namespaces containing extension binding
declarations are specified to a JAXB processor by the occurrence of the
global attribute _<jaxb:extensionBindingPrefixes>_ within an instance of
_<xs:schema>_ element. The value of this attribute is a
whitespace-separated list of namespace prefixes. The namespace bound to
each of the prefixes is designated as a customization declaration
namespace. Prefixes are resolved on the _<xs:schema>_ element that
carries this attribute. It is an error if the prefix fails to resolve.
This feature is quite similar to the extension-element-prefixes
attribute in [XSLT 1.0] _http://www.w3.org/TR/xslt10/#extension_ ,
introduces extension namespaces for extension instructions and functions
for XSLT 1.0.
This specification does not define any
mechanism for creating or processing extension binding declarations and
does not require that implementations support any such mechanism. Such
mechanisms, if they exist, are implementation-defined.
=== Inline Annotated Schema
This method of customization utilizes on the
_<appinfo>_ element specified by the XML Schema [XSD PART 1]. A binding
declaration is embedded within the _<appinfo>_ element as illustrated
below.
<xs:annotation> +
<xs:appinfo> +
_<binding declaration> +
_ </xs:appinfo> +
</xs:annotation>
The inline annotation where the binding
declaration is used identifies the schema component.
=== External Binding Declaration
The external binding declaration format
enables customized binding without requiring modification of the source
schema. Unlike inline annotation, the remote schema component to which
the binding declaration applies must be identified explicitly. The
_<jaxb:bindings>_ element enables the specification of a remote schema
context to associate its binding declaration(s) with. Minimally, an
external binding declaration follows the following format.
<jaxb:bindings [schemaLocation =
"xs:anyURI"]> +
<jaxb:bindings [node = "xs:string"]>* +
<binding declaration> +
<jaxb:bindings> +
</jaxb:bindings>
The schemaLocation attribute is optional for
specifying _<jaxb:globalBindings>_ , and The node attribute is optional
for specifying _<jaxb:schemaBindings>_ . The attributes _schemaLocation_
and _node_ are used to construct a reference to a node in a remote
schema. The binding declaration is applied to this node by the binding
compiler as if the binding declaration was embedded in the node’s
_<xs:appinfo>_ element. The attribute values are interpreted as follows:
* _schemaLocation -_ It is a URI reference
to a remote schema.
* _node_ - It is an XPath 1.0 expression
that identifies the schema node within schemaLocation to associate
binding declarations with.
An example external binding declaration can
be found in link:jaxb.html#a4821[See Example].”
=== Restrictions
* The external binding element
_<jaxb:bindings>_ is only recognized for processing by a JAXB processor
when its parent is an _<xs:appinfo>_ element, it is an ancestor of
another _<jaxb:bindings>_ element, or when it is root element of a
document. An XML document that has a _<jaxb:bindings>_ element as its
root is referred to as an external binding declaration file.
* The top-most _<jaxb:binding>_ element
within an _<xs:appinfo>_ element or the root element of an external
binding file must have its _schemaLocation_ attribute set.
=== Version Attribute
The normative binding schema specifies a
global _version_ attribute. It is used to identify the version of the
binding declarations. For example, a future version of this
specification may use the version attribute to specify backward
compatibility. To indicate this version of the specification, the
_version should_ be _"2.0"._ It is also valid for @version to be “1.0”.
If any other version is specified, it must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].”
The _version_ attribute must be specified in
one of the following ways:
* If customizations are specified in inline
annotations, the _version_ attribute must be specified in _<xs:schema>_
element of the source schema. For example,
<xs:schema jaxb:version="2.0">
* If customizations are specified in an
external binding file, then the _jaxb:version_ attribute must be
specified in the root element _<jaxb:bindings>_ in the external binding
file. Alternately, a local _version_ attribute may be used. Thus the
version can be specified either as
<jaxb:bindings version="2.0" ... />
or
<jaxb:bindings jaxb:version="2.0" ... />
Specification of both _version_ and
_<jaxb:version>_ must result in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations].”
=== [[a1544]]Invalid Customizations
A non conforming binding declaration is a
binding declaration in the _jaxb_ namespace but does not conform to this
specification. A non conforming binding declaration results in a
customization error. The binding compiler must report the customization
error. The exact error is not specified here. For additional
requirements see link:jaxb.html#a3815[See Compatibility].”
The rest of this chapter assumes that non
conforming binding declarations are processed as indicated above and
their semantics are not explicitly specified in the descriptions of
individual binding declarations.
=== Notation
The source and binding-schema fragments shown
in this chapter are meant to be illustrative rather than normative. The
normative syntax for the binding language is specified in
link:jaxb.html#a4270[See Normative Binding Schema Syntax].” in
addition to the other normative text within this chapter. All examples
are non-normative.
* Metavariables are in italics.
* Optional attributes are enclosed in _[
square="bracket" ]_ .
* Optional elements are enclosed in _[
<elementA> ... </elementA> ]_ .
* Other symbols: ‘ _,_ ” denotes a sequence,
‘ _|_ ’ denotes a choice, ‘ _+_ ’ denotes one or more, ‘ _*_ ’ denotes
zero or more.
* The prefix _xs:_ is used to refer to schema
components in W3C XML Schema namespace.
* In examples, the binding declarations as
well as the customized code are shown in bold like this: <appinfo>
<annotation> or getAddress().
=== Naming Conventions
The naming convention for XML names in the
binding language schema are:
* The first letter of the first word in a
multi word name is in lower case.
* The first letter of every word except the
first one is in upper case.
For example, the XML name for the Java
property basetype is baseType.
=== Customization Overview
A binding declaration customizes the default
binding of a schema element to a Java representation. The binding
declaration defines one or more customization values each of which
customizes a part of Java representation.
=== Scope
When a customization value is defined in a
binding declaration, it is associated with a scope. A scope of a
customization value is the set of schema elements to which it applies.
If a customization value applies to a schema element, then the schema
element is said to be covered by the scope of the customization value.
The scopes are:
* global scope: A customization value defined
in _<globalBindings>_ has global scope. A global scope covers all the
schema elements in the source schema and (recursively) any schemas that
are included or imported by the source schema.
* schema scope: A customization value defined
in <schemaBindings> has schema scope. A schema scope covers all the
schema elements in the target namespace of a schema.
* definition scope: A customization value in
binding declarations of a type definition or global declaration has
definition scope. A definition scope covers all schema elements that
reference the type definition or the global declaration. This is more
precisely specified in the context of binding declarations later on in
this chapter.
* component scope: A customization value in a
binding declaration has component scope if the customization value
applies only to the schema element that was annotated with the binding
declaration.
image:xmlb-18.png[image]
=== Scoping Inheritance and Overriding For Binding Declarations
The different scopes form a taxonomy. The
taxonomy defines both the inheritance and overriding semantics of
customization values. A customization value defined in one scope is
inherited for use in a binding declaration covered by another scope as
shown by the following inheritance hierarchy:
* a schema element in schema scope inherits a
customization value defined in global scope.
* a schema element in definition scope
inherits a customization value defined in schema or global scope.
* a schema element in component scope
inherits a customization value defined in definition, schema or global
scope.
Likewise, a customization value defined in
one scope can override a customization value inherited from another
scope as shown below:
* value in schema scope overrides a value
inherited from global scope.
* value in definition scope overrides a value
inherited from schema scope or global scope.
* value in component scope overrides a value
inherited from definition, schema or global scope.
=== XML Schema Parsing
Chapter 5 specified the bindings using the
abstract schema model. Customization, on the other hand, is specified in
terms of XML syntax not abstract schema model. The XML Schema
specification [XSD PART 1] specifies the parsing of schema elements into
abstract schema components. This parsing is assumed for parsing of
annotation elements specified here. In some cases, [XSD PART 1] is
ambiguous with respect to the specification of annotation elements.
link:jaxb.html#a2217[See Annotation Restrictions]” outlines how
these are addressed.
*
=== [[a1580]] _<globalBindings>_ Declaration
The customization values in “<
_globalBindings>_ ” binding declaration have global scope. This binding
declaration is therefore useful for customizing at a global level.
=== [[a1582]]Usage
<globalBindings +
[ collectionType = "collectionType" ] +
[ fixedAttributeAsConstantProperty = "true" | "false" | "1" | "0" ] +
[ generateIsSetMethod = "true" | "false" | "1" | "0" ] +
[ enableFailFastCheck = "true" | "false" | "1" | "0" ] +
[ choiceContentProperty = "true" | "false" | "1" | "0" ] +
[ underscoreBinding = "asWordSeparator" | "asCharInWord" ] +
[ typesafeEnumBase = "typesafeEnumBase" ] +
[ typesafeEnumMemberName = "skipGeneration" | +
"generateName" | "generateError" ] +
[ typesafeEnumMaxMembers = “xxxx”] +
[ enableJavaNamingConventions = "true" | "false" | "1" | "0" ] +
[ generateElementClass = "false" | "true" | "0" | "1" ] +
[ generateElementProperty = "false" | "true" | "0" | "1" ] +
[ generateValueClass = "true" | "true" | "0" | "1" ] +
[ optionalProperty = "wrapper" | "primitive" | "isSet" ] +
[ mapSimpleTypeDef = "true" | "false" | "1" | "0" ] +
[ localScoping = "nested" | "toplevel" ] > +
[ <javaType> ... </javaType> ]* +
[ <serializable uid=”xxxx”/> ]* +
</globalBindings>
The following customization values are
defined in global scope:
* _collectionType_ if specified, must be
either “ _indexed"_ or any fully qualified class name that implements
_java.util.List._ The default value is to any fully qualified class name
that implements _java.util.List_ .
* _fixedAttributeAsConstantProperty_ if
specified , defines the customization value
_fixedAttributeAsConstantProperty_ . The value must be one of _"true",
false", "1" or"0"._ The default value is _"false"_ .
* _generateIsSetMethod_ if specified,
defines the customization value of _generateIsSetMethod._ The value must
be one of _"true", false", "1" or"0"._ The default value is _"false"_ .
Consider customizing using the newly introduced _optionalProperty_
before using this JAXB 1.0 customization.
* _enableFailFastCheck_ if specified,
defines the customization value _enableFailFastCheck._ The value must be
one of _"true", "false", "1" or"0"._ If enableFailFastCheck is "true" or
"1" and the JAXB implementation supports this optional checking, type
constraint checking when setting a property is performed as described in
link:jaxb.html#a541[See Properties]". The default value is
_"false"_ .
* _choiceContentProperty_ if
specified,defines the customization value _choiceContentProperty_ . The
value must be one of _"true", false", "1" or"0"._ The default value is
_"false"_ .
* _underscoreBinding_ if specified, defines
the customization value _underscoreBinding_ . The value must be one of
_"asWordSeparator" or "asCharInWord"._ The default value is
_"asWordSeparator"_ .
* _enableJavaNamingConventions_ if
specified, defines the customization value _enableJavaNamingConventions_
. The value must be one of _"true", false", "1" or"0"._ The default
value is _"true"_ .
* _typesafeEnumBase_ if specified, defines
the customization value _typesafeEnumBase._ The value must be a list of
QNames, each of which must resolve to a simple type definition. Only
simple type definitions with an enumeration facet and a restriction base
type listed in _typesafeEnumBase_ or derived from a type listed in
_typesafeEnumBase_ is bound to a _typesafeEnumClass_ by default as
specified in link:jaxb.html#a829[See Enum Type]". The default
value of _typesafeEnumBase_ is _“xs:string”._
The _typesafeEnumBase_ cannot contain the
following simple types and therefore a JAXB implementation is not
required to support the binding of the these types to typesafe
enumeration class: _"xs:QName", "xs:NOTATIION”, xs:base64Binary",
"xs:hexBinary", "xs:date", "xs:time", "xs:dateTime", "xs:duration",
"xs:gDay", "xs:gMonth", "xs:gYear", "xs:gMonthDay", "xs:gYearMonth",
“xs:IDREF”, “xs:ID”._ If any of them are specified, it must result in an
invalid customization as specified in link:jaxb.html#a1544[See
Invalid Customizations].” JAXB implementation must be capable of binding
any other simple type listed in _typesafeEnumBase_ to a typesafe
enumeration class.
* _typesafeEnumMemberName_ if specified,
defines the customization value _typesafeEnumMemberName._ The value must
be one of _skipGeneration_ , _generateError_ or _generateName._ The
default value is _skipGeneration_ . See link:jaxb.html#a1633[See
@typesafeEnumMemberName]” for details.
* _typesafeEnumMaxMembers_ if specified,
defines the maximum number of enum facets that a simple type definition
can have and be consider to binding to an enum type by default. The
attributes type is _xs:int_ and its default value is _256_ .
* _generateElementClass_ if specified as
true, a schema-derived Element class, as specified in
link:jaxb.html#a657[See Java Element Class]”, is generated for
each element declaration that has an element factory method generated
for it. Its default value is false.
* _generateElementProperty_ if specified as
true, controls the generation of JAXBElement property. The value must be
one of "true", "false", "1", or "0". The default is absence of the
value.
* _generateValueClass_
if specified as true, a
schema-derived Java value class is generated for each complex type
definiton.Value class is specified in link:jaxb.html#a521[See
Value Class]. If generateValueClass is specified as false, a
schema-derived interface and implementation class is generated for each
complex type definition as specified in link:jaxb.html#a536[See
Java Content Interface]”. The attribute’s default value is true. See
examples of this binding in link:jaxb.html#a1617[See
generateElementClass and generateValueClass]”.
* zero or more _javaType_ binding
declarations. Each binding declaration must be specified as described in
link:jaxb.html#a1981[See <javaType> Declaration].”
* zero or one serializable binding
declaration.
* _optionalProperty_
controls how a JAXB property with a
primitive base type that represents an optional non-nillable
element/attribute is bound. If the attribute has the value "wrapper",
then the base type of the JAXB property is the wrapper class for the
primitive type. A user can indicate that this optional property is not
set by calling the setter with “null” value. If the attribute’s value is
"primitive", it binds as it did in JAXB 1.0. If the attribute’s value is
“isSet”, it binds the optional property using the primitive base type
and also the isSet/unset methods are generated for the optional
property. The attribute’s default value is “wrapper”.
* _mapSimpleTypeDef_ controls whether a JAXB
mapped class should be generated for each simple type definition as
specified in link:jaxb.html#a803[See Bind to a JAXB mapped
class]”. This attribute’s default value is _false_ . This customization
eases preserving simple type substituting precisely as described in
link:jaxb.html#a1158[See Type Substitution of a Simple Type
Definition]”.
* _localScoping_ attribute can have the
value of either _nested_ or _toplevel_ . This attribute describes the
JAXB binding of nested XML schema component to either a _nested_
schema-derived JAXB class or a _toplevel_ schema-derived JAXB class. To
avoid naming collisions between nested components, the default value for
this attribute is _nested_ . A developer can customize _localScoping_ to
_toplevel_ w hen schema components nest too deeply or an application
would prefer to not work with nested classes.
The semantics of the above customization
values, if not specified above, are specified when they are actually
used in the binding declarations.
For inline annotation, a _<globalBindings>_
is valid only in the annotation element of the _<schema>_ element. There
must only be a single instance of a _<globalBindings>_ declaration in
the annotation element of the _<schema>_ element.
=== [[a1608]]Customized Name Mapping
A customization value can be used to specify
a name for a Java object (e.g. class name, package name etc.). In this
case, a customization value is referred to as a customization name.
A customization name is always a legal Java
identifier (this is formally specified in each binding declaration where
the name is specified). Since customization deals with customization of
a Java representation to which an XML schema element is bound, requiring
a customization name to be a legal Java identifier rather than an XML
name is considered more meaningful.
A customization name may or may not conform
to the recommended Java language naming conventions. [JLS - Java
Language Specification, Second Edition, Section 6.8, “Naming
Conventions”]. The customization value enableJavaNamingConventions
determines if a customization name is mapped to a Java identifier that
follows Java language naming conventions or not.
If enableJavaNamingConventions is defined and
the value is _"true"_ or _"1",_ then the customization name (except for
constant name) specified in the section from where this section is
referenced must be mapped to Java identifier which follows the Java
language naming conventions as specified in
link:jaxb.html#a4816[See Conforming Java Identifier Algorithm]”;
otherwise the customized name must be used as is.
=== [[a1613]]Underscore Handling
The _[jaxb:globalBindings]_ attribute
customization _underscoreBinding_ allows for the preservation of
underscore(s) occurring in an XML name when deriving a a Java identifier
from it.
The default value for _@underscoreBinding_ is
_"asWordSeparator"_ and categorizes underscore, ‘_’, as a punctuation
mark in the XML name to Java identifier algorithm specified in Appendix
link:jaxb.html#a4656[See The Name to Identifier Mapping
Algorithm]. The resulting algorithm transforms one or more consecutive
underscores in an XML name to camel case separated words in the derived
Java class and method names. Examples of this mapping are in
link:jaxb.html#a4734[See XML Names and derived Java Class,
Method, and Constant Names].
When @ _underscoreBinding_ is
_"asCharInWord",_ underscore (‘_’) is considered a special letter within
a word. The result is that all underscore characters from the original
XML name are preserved in the derived Java identifier. Example of this
mapping are in link:jaxb.html#a4755[See XML Names and derived
Java Class, Method, and Constant Names when <jaxb:globalBindings
underscoreHandling=”asCharInWord”>].
=== [[a1617]]generateElementClass and generateValueClass
The following code examples illustrate
default binding to value class and customization to bind to
interface/implementation classes.
=== Default Binding to a value class.
Schema fragment:
<xs:complexType name=”USAddress”> +
<xs:attribute name=”City” type=”xs:string”/>
</xs:complexType>
Default Value Class:
public class USAddress \{ +
public USAddress() \{... } +
public String getCity() \{....} +
public void setCity(String value) \{...} +
... +
}
Customization _<jaxb:globalBinding
generateValueClass=”false”>_ generates following interface instead of
default value class:
=== Customized binding to an interface.
public interface USAddress \{ +
String getCity(); +
void setCity(String value); +
}
=== Generation of an Element Class
Schema fragment:
<xs:element name=”Address”
type=”USAddress”/> +
+
// Default Java binding of global element to element instance factory +
public ObjectFactory \{ +
JAXBElement<USAddress> createAddress(USAddress value); +
}
_<jaxb:globalBinding
generateElementClass=”true”/>_ results in generation of following
Element class:
+
public class Address extends JAXBElement<USAddress> \{ +
}
=== [[a1633]]@typesafeEnumMemberName
.If there is a collision among the generated
constant fields _name_ or if it is not possible to generate a legal Java
identifier for one or more of the generated constant field names, then
the binding is determined based on the value of @
_typesafeEnumMemberName_ of element _[jaxb:globalBindings]_ .
* _skipGeneration +
_ An enum type is not generated. This is the default behavior if
_typesafeEnumMemberName_ has not been specified. A binding compiler may
report a warning on why the simple type definition was not bound to an
enum type.
* _generateName +
_ The constant fields _name_ is “ _VALUE__ _<N>_ _"_ where _<N>_ is 1
for the first enumeration value and increments by 1 to represent each
value within the XML enumeration.
* _generateError +
_ An error must be reported.
=== <serializable> Declaration
When the serializable customization is
specified, all schema-derived classes implement _java.io.Serializable_ .
Each class is generated with a _serialVersionUID_ field set to the value
specified by _@uid_ .
private static final long serialVersionUID =
_<value of @uid>_ ;
The JAXB user is required to identify when
schema-derived classes do not follow
_http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/version.html#wp4602[Java
serialization class evolution rules]_ and change the generated
_serialVersionUID_ field by changing the [serializable] element’s
attribute _@uid_ value.
=== @generateElementProperty
Some schemas use both minOccurs="0" on
element as well as nillable="true", causing the generation of
JAXBElement. This customization lets you control this behavior. This
attribute may take two values:
* _true: +
_ Always generate properties to use JAXBElement, unless overriden by
_<jaxb:property generateElementProperty=”false”/>_ on individual
property.
* _false: +
_ When generating properties from _<element nillable=”true”
minOccurs=”0”/>_ , generate a property not to use JAXBElement, as if the
element declaration were just _<element nillable=”true” />_ , unless
overriden by _<jaxb:property generateElementProperty=”true”/>_ on
individual property. It is an error to specify this customization, when
the property is required to be JAXBElement (such as when a property
contains multiple elements with different names but of the same type.)
=== _<schemaBindings>_ Declaration
The customization values in
_<schemaBindings>_ binding declaration have schema scope. This binding
declaration is therefore useful for customizing at a schema level.
=== Usage
<schemaBindings [ map="boolean" ] >
{empty} [ <package> package </package> ]
[ <nameXmlTransform> ... </nameXmlTransform>
]*
</schemaBindings>
{empty}<package [ name = "packageName" ]
{empty} [ <javadoc> ... </javadoc> ]
</package>
<nameXmlTransform>
{empty} [ <typeName [ suffix="suffix" ]
{empty} [ prefix="prefix" ] /> ]
{empty} [ <elementName [ suffix="suffix" ]
{empty} [ prefix="prefix" ] /> ]
{empty} [ <modelGroupName [ suffix="suffix" ]
{empty} [ prefix="prefix" ] /> ]
{empty} [ <anonymousTypeName [
suffix="suffix" ]
{empty} [ prefix="prefix" ] /> ]
</nameXmlTransform>
For readability, the _<nameXmlTransform>_ and
_<package>_ elements are shown separately. However, they are local
elements within the _<schemaBindings>_ element.
The following customizations are defined in
the schema scope:
* _map_ if specified, prevents the classes
from being generated from this schema. When the value is “0” or “false”,
then no class/interface/enum will be generated from this package. map
defaults to true.
The semantics of the customization value, if
not specified above, are specified when they are actually used in the
binding declarations.
For inline annotation, a _<schemaBindings>_
is valid only in the annotation element of the _<schema>_ element. There
must only be a single instance of a _<schemaBindings>_ declaration in
the annotation element of the _<schema>_ element.
If one source schema includes (via the
include mechanism specified by XSD PART 1) a second source schema, then
the _<schemaBindings>_ declaration must be declared in the first
including source schema. It should be noted that there is no such
restriction on _<schemaBindings>_ declarations when one source schema
imports another schema since the scope of _<schemaBindings>_ binding
declaration is schema scope.
=== package __ [[a1674]]
Usage
* _name_ if specified, defines the
customization value _packageName_ . _packageName_ must be a valid Java
package name.
* < _javadoc>_ if specified, customizes the
package level Javadoc. < _javadoc>_ must be specified as described in
link:jaxb.html#a2142[See <javadoc> Declaration].” The Javadoc
must be generated as specified in link:jaxb.html#a2163[See
Javadoc Customization].” The Javadoc section customized is the _package
section._
*
The semantics of the _packageName_ is
specified in the context where it is used. If neither _packageName_ nor
the < _javadoc>_ element is specified, then the binding declaration has
no effect.
=== Example: Customizing Package Name
<jaxb:schemaBindings>
<jaxb:package name = "org.example.po" />
</jaxb:schemaBindings>
specifies “ _org.example.po_ ” as the package
to be associated with the schema.
=== _nameXmlTransform_
The use case for this declaration is the UDDI
Version 2.0 schema. The UDDI Version 2.0 schema contains many
declarations of the following nature:
<xs:element name="bindingTemplate"
type="uddi:bindingTemplate"/>
The above declaration results in a name
collision since both the element and type names are the same - although
in different XML Schema symbol spaces. Normally, collisions are supposed
to be resolved using customization. However, since there are many
collisions for the UDDI V2.0 schema, this is not a convenient solution.
Hence the binding declaration _nameXmlTransform_ is being provided to
automate name collision resolution.
The _nameXmlTransform_ allows a _suffix_ and
a _prefix_ to be specified on a per symbol space basis. The following
symbol spaces are supported:
* _<typeName>_ for the symbol space “type
definitions”
* _<elementName>_ for the symbol space
“element definitions”
* _<modelGroupName>_ for the symbol space
“model group definitions.”
* _<anonymousTypeName>_ for customizing Java
value class to which an anonymous type is bound.link:#a5377[26]
If _suffix_ is specified, it must be appended
to all the default XML names in the symbol space. The _prefix_ if
specified, must be prepended to the default XML name. Furthermore, this
XML name transformation must be done after the XML name to Java
Identifier algorithm is applied to map the XML name to a Java
identifier. The XML name transformation must not be performed on
customization names.
By using a different _prefix_ and/or _suffix_
for each symbol space, identical names in different symbol spaces can be
transformed into non-colliding XML names.
_anonymousTypeName_
The _<anonymousTypeName>_ declaration can be
used to customize the suffix and prefix for the Java value class. If
_prefix_ is specified, then it must be prepended to the Java value class
name for the anonymous type. If suffix is specified, it must be
appended.
=== _<class>_ [[a1698]] Declaration
This binding declaration can be used to
customize the binding of a schema component to an element class, value
class or interface/implementation class. The customizations can be used
to specify:
* a name for the derived Java class.
* an alternative implementation of
interface/implementation binding.
Specification of an alternate implementation
for an interface allows implementations generated by a tool (e.g. based
on UML) to be used in place of the default implementation generated by a
JAXB provider.
The implementation class may have a
dependency upon the runtime of the binding framework. Since a runtime
was not specified for JAXB 1.0 interface/implementation binding, the
implementation class may not be portable across JAXB provider
implementations. Hence one JAXB provider implementation is not required
to support the implementation class from another JAXB provider.
=== Usage
{empty}<class [ name = " _className_ " ]
{empty} [ implClass = " _implClass_ " ]> +
[ ref = " _className_ " ]
{empty} [ <javadoc> _..._ </javadoc> ]
</class>
* _className_ is the name of the derived
value class, if specified. It must be a legal Java class name and must
not contain a package prefix. The package prefix is inherited from the
current value of package _._
* _implClass_ if specified, is the name of
the implementation class for _className_ and must include the complete
package name. Note that this customization only impacts the return value
for _className_ ’s factory method. This customization is ignored when
_new_ is used to create instances of a schema-derived Value class.
* _ref_ if specified, is the name of the
value class that is provided outside the schema compiler. This
customization causes a schema compiler to refer to this external class,
as opposed to generate a definition. It must include the complete
package name. This attribute is mutually exclusive with the _className_
attribute and the _implClass_ attribute.
* _<javadoc>_ element, if specified
customizes the Javadoc for the derived value class. _<javadoc>_ must be
specified as described in link:jaxb.html#a2142[See <javadoc>
Declaration].”
=== [[a1713]]Customization Overrides
When binding a schema element’s Java
representation to a value class or a Java Element class, the following
customization values override the defaults specified in Chapter 5. It is
specified in a common section here and referenced from
link:jaxb.html#a1718[See Customizable Schema Elements].”
* name: The name is _className_ if specified.
* package name: The name of the package is
_packageName_ inherited from a scope that covers this schema element. +
+
NOTE: The _packageName_ is only set in the <package> declaration. The
scope of _packageName_ is schema scope and is thus inherited by all
schema elements within the schema.
* javadoc: The Javadoc must be generated as
specified in section link:jaxb.html#a2163[See Javadoc
Customization].” The Javadoc section customized is the _class/interface
section._
=== [[a1718]]Customizable Schema Elements
=== Complex Type Definition
When _<class>_ customization specified in the
annotation element of the complex type definition, the complex type
definition must be bound to a Java value class as specified in
link:jaxb.html#a933[See Java value class]” applying the
customization overrides as specified in link:jaxb.html#a1713[See
Customization Overrides].”
=== Example: Class Customization: Complex Type Definition To Java value class
XML Schema fragment:
<xs:complexType name="USAddress"> +
<xs:annotation> <xs:appinfo> +
<jaxb:class name="MyAddress" /> +
</xs:appinfo></xs:annotation> +
<xs:sequence>...</xs:sequence> +
<xs:attribute name="country" type="xs:string"/> +
</xs:complexType>
Customized code:
// public class USAddress \{ // Default Code
public class MyAddress \{ // Customized Code
public String getCountry()\{...}
public void setCountry(String value)\{...}
...
}
=== Simple Type Definition
When _<class>_ customization specified in the
annotation element of a simple type definition, the simple type
definition must be bound to a Java value class as specified in
link:jaxb.html#a803[See Bind to a JAXB mapped class]” applying
the customization overrides as specified in
link:jaxb.html#a1713[See Customization Overrides].”
=== Example: Class Customization: Simple Type Definition To Java value class
XML Schema fragment:
<xs:simpleType name="SKU"> +
<xs:annotation> <xs:appinfo> +
<jaxb:class/> +
</xs:appinfo></xs:annotation> +
<xs:restriction base=”xs:int”/> +
</xs:simpleType>
Customized code:
public class SKU \{ +
@XmlValue +
public int getValue()\{...} +
public void setValue(int value)\{...} +
... +
}
=== Model Group Definition
It is invalid to place a _<jaxb:class>_
customization on a model group.
=== Model Group
It is invalid to place a _<jaxb:class>_
customization on an unnamed model group.
=== Global Element Declaration
A < _class_ > declaration is allowed in the
annotation element of the global element declaration. However, the
_implClass_ attribute is not allowed. The global element declaration
must be bound as specified in link:jaxb.html#a1068[See Bind to
Element Class]” applying the customization overrides specified in
link:jaxb.html#a1713[See Customization Overrides].”
=== Example: Class Customization: Global Element to Class
XML Schema Fragment:
<xs:complexType name="AComplexType">
<xs:sequence>
<xs:element name="A" type="xs:int"/>
<xs:element name="B" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="AnElement"
type="AComplexType">
<xs:annotation><xs:appinfo>
<jaxb:class name="MyElement"/>
</xs:appinfo></xs:annotation>
</xs:element>
Customized code:
// following class is generated because of
customization
public class AComplexType \{ +
void setA(int value) \{...}
int getA()\{...}
void setB(String value)\{...}
String getB()\{...}
}
public class MyElement extends
JAXBElement<AComplexType> \{...}
public class ObjectFactory \{
// Default code
// JAXBElement<AnElement>
createAnElement(AnElement)\{...} +
+
// Customized code
MyElement createMyElement(AnElement)\{...} +
... other factory methods ...
}
=== Local Element
A local element is a schema element that
occurs within a complex type definition. A local element is one of:
* local element reference (using the “ref”
attribute) to a global element declaration.
* local element declaration (“ref” attribute
is not used).
A _<class>_ declaration is allowed in the
annotation element of a local element. link:jaxb.html#a2217[See
Annotation Restrictions]” contains more information regarding the
annotation element for a local element reference. However, the
_implClass_ attribute is not allowed.
A _<class>_ customization on local element
reference must result in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations]” since a local
element reference is never bound to a Java Element class.
A _<class>_ customization on local element
declaration applies only when a local element declaration is bound to a
Java Element class. Otherwise it must result in an invalid customization
as specified in link:jaxb.html#a1544[See Invalid
Customizations].” If applicable, a local element must be bound as
specified in link:jaxb.html#a1040[See Bind to JAXBElement<T>
Instance]” applying the customization overrides as specified in
link:jaxb.html#a1713[See Customization Overrides].”
=== Example: Class Customization: Local Element Declaration To Java Element
The following example is from
link:jaxb.html#a1359[See Examples].”
XML Schema fragment:
<xs:complexType name="Base"> +
<xs:choice maxOccurs="unbounded"> +
<xs:element name="A" type="xs:string"> +
<xs:annotation><xs:appinfo> +
<jaxb:class name="Bar"/> +
< _/xs:appinfo></xs:annotation> +
_ </xs:element> +
<xs:element name="B" type="xs:string"/> +
<xs:element name="C" type="xs:int"/> +
</xs:choice> +
</xs:complexType>
Customized code:
import jakarta.xml.bind.JAXBElement; +
public class ObjectFactory \{ +
// element instance factories only +
// JAXBElement<String> createBaseA(String value); //default code +
JAXBElement<String> createBaseBar(String value); //Customized +
JAXBElement<String> createBaseB(String value); +
JAXBElement<Integer> createBaseC(Integer value); +
} +
public class Base \{ +
static public class Bar extends JAXBElement<String> \{...}// Customized
code +
/** +
* A general content list that can contain element +
* instances of JAXBElement<String> or JAXBElement<Integer>. +
*/ +
List<Object> getBarOrBOrC()\{...} +
}
=== [[a1783]] _<property>_ Declaration
This binding declaration allows the
customization of a binding of an XML schema element to its Java
representation as a property. This section identifies all XML schema
elements that can be bound to a Java property and how to customize that
binding.
The scope of customization value can either
be definition scope or component scope depending upon which XML schema
element the < _property>_ binding declaration is specified.
=== [[a1786]]Usage
<property [ name = "propertyName" ] +
[ collectionType = " _propertyCollectionType_ " ] +
[ fixedAttributeAsConstantProperty = "true" | "false" | "1" | "0" ] +
[ generateIsSetMethod = "true" | "false" | "1" | "0" ] +
[ enableFailFastCheck="true" | "false" | "1" | "0" ] +
[ generateElementProperty= “true” | “false” | “1” | “0” ] +
[ attachmentRef = “resolve” | “doNotResolve” | “default” ] +
[ <baseType name=”fully qualified Java class”> ... </baseType> ] +
[ <javadoc> ... </javadoc> ] +
</property> +
+
<baseType name=”fully qualified Java class”> +
<javaType> ... </javaType> +
</baseType>
For readability, the _<baseType>_ element is
shown separately. However, it can be used only as a local element within
the _<property>_ element.
The use of this declaration is subject to the
constraints specified in link:jaxb.html#a1825[See Usage
Constraints].”
The customization values defined are:
* _name_ if specified , defines the
customization value _propertyName;_ it must be a legal Java identifier.
* _collectionType_ if specified, defines the
customization value _propertyCollectionType_ which is the collection
type for the property. _propertyCollectionType_ if specified, must be
either “ _indexed"_ or any fully qualified class name that implements
_java.util.List._
* _fixedAttributeAsConstantProperty_ if
specified , defines the customization value
_fixedAttributeAsConstantProperty_ . The value must be one of _"true",
false", "1" or"0"._
* _generateIsSetMethod_ if specified,
defines the customization value of _generateIsSetMethod._ The value must
be one of _"true", false", "1" or"0"._
* _enableFailFastCheck_ if specified,
defines the customization value _enableFailFastCheck._ The value must be
one of _"true", false", "1" or"0"._
* _@generateElementProperty_ if specified,
controls the generation of JAXBElement property. The value must be one
of "true", "false", "1", or "0". The default is absence of the value. It
is an error for this attribute to be present if this customization is
attached to local or global attribute declarations. This customization
affects the binding as follows. It is an error to specify this
customization, when the property is required to be _JAXBElement_ (such
as when a property contains multiple elements with different names but
of the same type.)
* _true_ : Always generate properties to use
_JAXBElement_ .
* _false_ : When generating properties from
_<element nillable="true" minOccurs="0" />_ , generate a property not to
use JAXBElement, as if the element declaration were just _<element
nillable="true"/>_ .
* _@attachmentRef_ has a default value of
“default”. This mode defers to default processing as specified in
link:jaxb.html#a5147[See Binding WS-I Attachment Profile
ref:swaRef]”. +
+
When _@attachmentRef_ value is _resolve_ and the property’s base type is
or derives from _xsd:anyURI_ , the schema-derived JAXB property has a
base type of _javax.activation.DataHandler_ and the property is
annotated with _@XmlAttachmentRef_ . +
+
Disabling autoresolving an element/attribute of type _ref:swaRef_ : +
When _@attachmentRef_ value is _doNotResolve_ and the property’s base
type derives from standard schema type _ref:swaRef,_ the schema-derived
JAXB property has the base type _String_ , derived from _xsd:anyURI,_
and _@XmlAttachmentRef_ is not generated for the property.
* _<javadoc>_ element, if specified
customizes the Javadoc for the property’s getter method. _<javadoc>_
must be specified as described in link:jaxb.html#a2142[See
<javadoc> Declaration].”
=== _baseType_ [[a1801]]
The _<baseType>_ element is intended to allow
the customization of a base type for a JAXB property. This element can
only be a child of <jaxb:property> element.
<baseType name=”fully qualified Java
class”> +
<javaType> ... </javaType> +
</baseType>
The _@name_ attribute enables either the
specialization or generalization of the default base type binding for a
JAXB property. Child element _<javaType>_ is used to convert the default
base type to a Java class. These two mutual exclusive usages of the
<baseType> customization are described below.
=== Conversion using Child element <javaType>
Optional child element < _javaType>_ , if
specified, defines the customization value _javaType_ and must be
specified as defined in link:jaxb.html#a1981[See <javaType>
Declaration].” The customization value defined has component scope. This
customization converts the default base type’s value for a simple type
definition to the Java class specified by <javaType> name.
The schema-derived JAXB property is annotated
with _@XmlJavaTypeAdapter_ specified in Section 8.
_@XmlJavaTypeAdapter.value()_ is set to a generated
classlink:#a5378[27] that extends
_jakarta.xml.bind.annotation.adapter.XmlAdapter_ . The generated class’
_unmarshal_ method must call the <javaType> customization’s parse
method, which is specified in link:jaxb.html#a1981[See
<javaType> Declaration]. The generated class’ _marshal_ method must call
the <javaType> customization’s print method.
=== [[a1809]]Generalize/Specialize baseType with attribute @name
The _name_ attribute for _<baseType>_ enables
more precise control over the actual base type for a JAXB property. This
customization enables specifying an alternative base type than the
property’s default base type. The alternative base type must still be in
the same class inheritance hierarchy as the default base type. The
alternative base type must be either a super interface/class or subclass
of the default Java base type for the property. The customization
enables one to specialize or generalize the properties binding.
The _name_ attribute value must be a fully
qualified Java class name. When the default base type is a primitive
type, consider the default Java base type to be the Java wrapper class
of that primitive type.
Generalizing the basetype using this
customization enables simple type substitution for a JAXB property
representing with too restrictive of a default base type. To enable all
possible valid type substitutions, the _name_ attribute should be
_java.lang.Object_ . However, if for example, it is known that all type
substitutions will share a more specific Java super interface/class than
_java.lang.Object_ , that Java class name can be used achieve a stronger
typed binding. With this customization, the JAXB annotation generated
for the property’s _@XmlElement.type()_ or _@XmlAttribute.type()_ is
still the default Java datatype for the element/attribute’s
schema-defined type.
The schema-derived customized JAXB property
is annotated, either explicitly or by default mapping annotations, with
the mapping annotation _@XmlElement_ , specified in Section 8.10.1. The
_@XmlElement_ annotation element type is derived in terms of the
abstract model properties for a element type definition summarized in
link:jaxb.html#a4937[See Element Declaration Schema Component]
as follows:
=== Annotate JAXB property with @XmlElement element-value pairs
[width="100%",cols="50%,50%",options="header",]
|===
|@XmlElement element
|@XmlElement value
|type |the java
type binding of the element declaration’s _\{type definition}_
|===
Note that the Java class for
_@XmlElement.type()_ can differ from the recommended JAXB property’s
base type to enable type substitution of java.lang.Object. This binding
enables unmarshalling of the Element’s simple content when it is not
qualified with an _xsi:type_ as the element’s schema-declared type.
_@XmlElement.type()_ acts as the default _xsi:type_ for a JAXB property
where the property’s base type was generalized to allow for type
substitution of an element declaration with a simple type definition.
Specializing the basetype using this
customization generates stronger typing than default JAXB binding. For
example, an XML element or attribute of _xs:IDREF_ binds to
_java.lang.Object_ by default as specified in
link:jaxb.html#a1290[See Binding an IDREF component to a Java
property]”. If the schema only intends the reference to be to an element
that binds to a specific type, the baseType @name schema customization
can be used to specialize the binding.
=== [[a1820]]Specialize binding of an IDREF via customization
Given XML Schema fragment:
<xs:complexType name="Book"> +
<xs:sequence> +
_<xs:element name="author" type="xs:IDREF"/> +
_ _<xs:annotation><xs:appinfo> +
<jaxb:property> +
<jaxb:baseType name=”AuthorBio.class”/> +
</jaxb:property> +
</xs:appinfo></xs:annotation> +
_ <!-- ... --> +
</xs:sequence> +
</xs:complexType> +
<xs:complexType name="AuthorBio"> +
<xs:sequence><!-- ... --> </xs:sequence> +
_<xs:attribute name="name" type="xs:ID"/> +
_ </xs:complexType>
Schema-derived Java value class:
public class Book \{ +
@XmlIDREF +
AuthorBio getAuthor() \{...} +
void setAuthor(AuthorBio referencedObj)\{...} +
} +
public class AuthorBio\{ +
@XmlID +
String getName()\{...} +
void setName(String value)\{...} +
}
=== [[a1825]]Usage Constraints
The usage constraints on _<property>_ are
specified below. Any constraint violation must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].” The usage constraints are:
. The _<baseType>_ is only allowed with the
following XML schema elements from the link:jaxb.html#a1857[See
Customizable Schema Elements]”:
. Local Element,
link:jaxb.html#a1913[See Local Element].”
. Local Attribute,
link:jaxb.html#a1861[See Local Attribute].”
. ComplexType with simpleContent,
link:jaxb.html#a1976[See ComplexType].”
. <baseType> can either have a name attribute
or a <javaType>, they both can not exist at the same time.
. The _fixedAttributeAsConstantProperty_ is
only allowed with a local attribute, link:jaxb.html#a1861[See
Local Attribute]" , that is fixed.
. If a _<property>_ declaration is associated
with the _<complexType>_ , then a _<property>_ customization cannot be
specified on the following schema elements that are scoped to
_<complexType>_ :
. Local Element
. Model group
. Model Group Reference
The reason is that a _<property>_ declaration
associated with a complex type binds the content model of the complex
type to a general content property. If a _<property>_ declaration is
associated with a schema element listed above, it would create a
conflicting customization.
*
=== Example: Property Customization: simple type customization
<xs:complexType name="internationalPrice"> +
.... +
<xs:attribute name="currency" type="xs:string"> +
<xs:annotation> <xs:appinfo> +
<jaxb:property> +
<jaxb:baseType> +
<jaxb:javaType name="java.math.BigDecimal" +
parseMethod="jakarta.xml.bind.DatatypeConverter.parseInteger" +
printMethod="jakarta.xml.bind.DatatypeConverter.printInteger"/> +
</jaxb:baseType> +
</jaxb:property> +
</xs:appinfo></xs:annotation> +
</xs:attribute> +
</xs:complexType>
The code generated is:
public class InternationalPrice \{
// String getCurrency(); default
java.math.BigDecimal getCurrency()\{...} //
customized
public void setCurrency(java.math.BigDecimal
val)\{...} // customized
}
=== [[a1847]]Customization Overrides
When binding a schema element’s Java
representation to a property, the following customization values
override the defaults specified in Chapter 6. It is specified in a
common section here and referenced from link:jaxb.html#a1857[See
Customizable Schema Elements].”
* name: If propertyName is defined, then it
is the name obtained by mapping the name as specified in
link:jaxb.html#a1608[See Customized Name Mapping].”
* base type: The basetype is
_propertyBaseType_ if defined. The propertyBaseType is defined by a XML
schema element in link:jaxb.html#a1857[See Customizable Schema
Elements].”
* collection type: The collection type is
_propertyCollectionType_ if specified; otherwise it is the
_propertyCollectionType_ inherited from a scope that covers this schema
element.
* javadoc: The Javadoc must be generated as
specified in section link:jaxb.html#a2163[See Javadoc
Customization].” The Javadoc section customized is the _method section._
* If _propertyBaseType_ is a Java primitive
type and _propertyCollectionType_ is a class that implements
java.util.List, then the primitive type must be mapped to its wrapper
class.
The following does not apply if local
attribute is being bound to a constant property as specified in
link:jaxb.html#a1861[See Local Attribute]”:
* If generateIsSetMethod is “true” or “1”,
then additional methods as specified in link:jaxb.html#a610[See
isSet Property Modifier]” must be generated.
* If enableFailFastCheck is “true” or “1”
then the type constraint checking when setting a property is enforced by
the JAXB implementation. Support for this feature is optional for a JAXB
implementation in this version of the specification.
=== [[a1857]]Customizable Schema Elements
=== Global Attribute Declaration
A < _property_ > declaration is allowed in
the annotation element of the global attribute declaration.
The binding declaration does not bind the
global attribute declaration to a property. Instead it defines
customization values that have definition scope. The definition scope
covers all local attributes (link:jaxb.html#a1861[See Local
Attribute]”) that can reference this global attribute declaration. This
is useful since it allows the customization to be done once when a
global attribute is defined instead of at each local attribute that
references the global attribute declaration.
=== [[a1861]]Local Attribute
A local attribute is an attribute that occurs
within an attribute group definition, model group definition or a
complex type. A local attribute can either be a
* local attribute reference (using the “ref”
attribute) to a global attribute declaration.
* local attribute declaration (“ref”
attribute is not used).
A < _property_ > declaration is allowed in
the annotation element of a local
attribute.link:jaxb.html#a2217[See Annotation Restrictions]”
contains more information regarding the annotation element for a local
attribute reference. The customization values must be defined as
specified in link:jaxb.html#a1786[See Usage]” and have component
scope.
If _javaType_ is defined, then the
_propertyBaseType_ is defined to be Java datatype specified in the
_"name"_ attribute of the _javaType_ .
* If _fixedAttributeAsConstantProperty_ is “
_true"_ or “ _1"_ and the local attribute is a fixed, the local
attribute must be bound to a Java Constant property as specified in
link:jaxb.html#a1277[See Bind to a Java Constant property]”
applying customization overrides as specified in
link:jaxb.html#a1847[See Customization Overrides].” The
generateIsSetMethod, choiceContentProperty and enableFailFastCheck must
be considered to have been set to false.
* Otherwise, it is bound to a Java property
as specified in link:jaxb.html#a1252[See Attribute use]”
applying customization overrides as specified in
link:jaxb.html#a1847[See Customization Overrides].”
=== Example: Customizing Java Constant Property
XML Schema fragment:
<xs:complexType name="USAddress">
<xs:attribute name="country"
type="xs:NMTOKEN" fixed="US">
<xs:annotation><xs:appinfo>
<jaxb:property name="MY_COUNTRY"
fixedAttributeAsConstantProperty="true"/>
</xs:appinfo></xs:annotation>
</xs:attribute>
</xs:complexType>
Customized derived code:
public class USAddress \{
public static final String MY_COUNTRY =
"US"; // Customized Code
}
=== Example 2: Customizing to other Java Property
XML Schema fragment:
<xs:complexType name="USAddress"> +
<xs:attribute name="country" type="xs:string">
<xs:annotation><xs:appinfo>
<jaxb:property name="MyCountry"/>
</xs:appinfo></xs:annotation>
</xs:attribute>
</xs:complexType>
Customized derived code:
public class USAddress \{
// public getString getCountry(); // Default
Code
// public void setCountry(string value);//
Default Code
public String getMyCountry()\{...} //
Customized Code
public void setMyCountry(String value)\{...}
// Customized Code
}
=== Example 3: Generating IsSet Methods
XML Schema fragment:
<xs:attribute name="account" type = "xs:int">
<xs:annotation><xs:appinfo>
<jaxb:property generateIsSetMethod="true"/>
</xs:appinfo></xs:annotation>
</xs:attribute>
Customized code:
public int getAccount();
public void setAccount(int account);
public boolean isSetAccount(); // Customized
code
public void unsetAccount(); // Customized
code
=== Global Element Declaration
A _<property>_ declaration is allowed in the
annotation element of a global element declaration. However, the usage
is constrained as follows:
The binding declaration does not bind the
global element declaration to a property. Instead it defines
customization values that have definition scope. The definition scope
covers all local elements (link:jaxb.html#a1913[See Local
Element]”) that can reference this global element declaration. This is
useful since it allows the customization to be done once when a global
element is defined instead of at each local element that references the
global element declaration.
=== [[a1913]]Local Element
A local element is a schema element that
occurs within a complex type definition. A local element is one of:
* local element reference (using the “ref”
attribute) to a global element declaration.
* local element declaration (“ref” attribute
is not used).
A <property> declaration is allowed in the
annotation element of a local element. link:jaxb.html#a2217[See
Annotation Restrictions]” contains more information regarding the
annotation element for a local element reference.
The customization values must be defined as
specified in link:jaxb.html#a1786[See Usage]” and have component
scope.
If _javaType_ is defined, then the
_propertyBaseType_ is defined to be Java datatype specified in the
_"name"_ attribute of the _javaType_ .
The local element must be bound as specified
in link:jaxb.html#a1414[See Content Model Default Binding]”
applying customization overrides as specified in
link:jaxb.html#a1847[See Customization Overrides].”
See example in
link:jaxb.html#a1966[See Example 3: Property Customization:
Model Group To Content Property Set]” in section
link:jaxb.html#a1944[See Model Group].”
=== Wildcard
A _<property>_ declaration is allowed in the
annotation element of the wildcard schema component. The customization
values must be defined as specified in link:jaxb.html#a1786[See
Usage]” and have component scope.
The wildcard schema component must be bound
to a property as specified in link:jaxb.html#a1384[See Bind
wildcard schema component]” applying customization overrides as
specified in link:jaxb.html#a1847[See Customization Overrides].”
Example: The following schema example is from
UDDI V2.0
<xs:complexType name="businessEntityExt">
<xs:sequence>
<xs:any namespace="##other"
processContents="strict"
minOccurs="1" maxOccurs="unbounded">
<xs:annotation><xs:appinfo>
<jaxb:property name="Extension"/>
</xs:appinfo></xs:annotation>
</xs:any>
....
</xs:sequence>
</xs:complexType>
Customized derived code:
public class BusinessEntityExt \{
...
// List getAny(); // Default Code
List getExtension()\{...} // Customized Code
}
=== [[a1944]]Model Group
A _<property>_ binding declaration is allowed
in the annotation element of the compositor (i.e. _<choice>_ ,
_<sequence>_ or _<all>_ ). The customization values must be defined as
specified in link:jaxb.html#a1786[See Usage]” and have component
scope.
The customized binding of a model group is
determined by the following:
* _choiceContentProperty_ attribute in
_<globalBindings>_ .
* If propertyBaseType is defined and a
_<property>_ declaration is also present, then the customization
overrides specified in link:jaxb.html#a1847[See Customization
Overrides]” must be applied by the model group’s parent schema element
to the property used to aggregate the Java value class.
* If propertySet is defined, then the model
group’s parent schema element must aggregate the property set as
specified in link:jaxb.html#a930[See Aggregation of Property
Set].”
=== Example1: Property Customization: Model Group To ChoiceContent Property
XML Schema fragment
<xs:annotation><xs:appinfo> +
<jaxb:globalBindings choiceContentProperty="true"/> +
</xs:appinfo></xs:annotation>
<xs:complexType name=”AType”> +
<xs:choice>
<xs:element name="foo" type="xs:int"/>
<xs:element name="bar" type="xs:string"/>
</xs:choice> +
</xs:complexType>
Customized derived code:
class ObjectFactory \{ +
JAXBElement<Integer> createAtypeFoo(Integer value); +
JAXBElement<String> createAtypeBar(String value);
} +
public class AType \{ +
void setFooOrBar(Object o)\{...} //customized code +
Object getFooOrBar()\{...} //customized code +
}
The _choiceContentProperty_ is required to
bind the choice model group to a choice content property.
=== Example 2: Property Customization: Model Group To General Content Property
XML Schema fragment:
<xs:complexType name="Base"> +
<xs:choice maxOccurs="unbounded"> +
<xs:annotation><xs:appinfo> +
<jaxb:property name="items" /> +
</xs:appinfo></xs:annotation> +
<xs:element name="A" type="xs:string"/> +
<xs:element name="B" type="xs:string"/> +
<xs:element name="C" type="xs:int"/> +
</xs:choice> +
</xs:complexType>
Customized derived code:
public class Base \{ +
/** +
* A general content list that can contain +
* instances of Base.A, Base.B and Base.C. +
*/ +
// List getAOrBOrC(); - default +
List getItems()\{...} // Customized Code +
}
=== [[a1966]]Example 3: Property Customization: Model Group To Content Property Set
XML Schema fragment:
<xs:complexType name="USAddress"/> +
<xs:complexType name="PurchaseOrderType"> +
<xs:sequence> +
<xs:choice> +
<xs:group ref="shipAndBill"/> +
<xs:element name="singleUSAddress" type="USAddress"> +
<xs:annotation><xs:appinfo> +
<jaxb:property name="address"/> +
</xs:appinfo></xs:annotation> +
</xs:element> +
</xs:choice> +
</xs:sequence> +
</xs:complexType>
<xs:group name="shipAndBill"> +
<xs:sequence> +
<xs:element name="shipTo" type="USAddress"> +
<xs:annotation><xs:appinfo> +
<jaxb:property name="shipAddress"/> +
</appinfo></annotation> +
</xs:element> +
<xs:element name="billTo" type="USAddress"> +
<xs:annotation><xs:appinfo> +
<jaxb:property name="billAddress"/> +
</xs:appinfo></xs:annotation> +
</xs:element> +
</xs:sequence> +
</xs:group>
Customized derived code:
public interface PurchaseOrderType \{
USAddress getShipAddress(); void
setShipAddress(USAddress); +
USAddress getBillAddress(); void setBillAddress(USAddress); +
USAddress getAddress(); void setAddress(USAddress); +
}
=== Model Group Reference
A model group reference is a reference to a
model group using the “ref” attribute. A property customization is
allowed on the annotation property of the model group reference. Section
link:jaxb.html#a2217[See Annotation Restrictions]” contains more
information regarding the annotation element for a model group
reference.
The customization values must be defined as
specified in link:jaxb.html#a1786[See Usage]” and have component
scope. A model group reference is bound to a Java property set or a list
property as specified in link:jaxb.html#a1414[See Content Model
Default Binding]” applying customization overrides as specified in
link:jaxb.html#a1847[See Customization Overrides].”
=== [[a1976]]ComplexType
A _<property>_ customization is allowed on
the annotation element of a complex type. The customization values must
be defined as specified in link:jaxb.html#a1786[See Usage]” and
have component scope. The result of this customization depends upon the
content type of the complex type.
* If the content type of the content model is
simple content, then the content model must be bound to a property as
specified in link:jaxb.html#a973[See Simple Content Binding].”
applying the customization overrides as specified in
link:jaxb.html#a1847[See Customization Overrides].” If
_javaType_ is defined, then the _propertyBaseType_ is defined to be Java
datatype specified in the _"name"_ attribute of the _javaType_ .
* For all other content types, the content
model must be bound as specified in step 1. of
link:jaxb.html#a1414[See Content Model Default Binding]”
applying the customization overrides as specified in
link:jaxb.html#a1847[See Customization Overrides]".
*
=== [[a1981]] _<javaType>_ Declaration
A _<javaType>_ declaration provides a way to
customize the binding of an XML schema atomic datatype to a Java
datatype, referred to as the target Java datatype. The target Java
datatype can be a Java built-in data type or an application specific
Java datatype. This declaration also provides two additional methods: a
parse method and a print method.
The parse method converts a lexical
representation of the XML schema datatype into a value of the target
Java datatype. The parse method is invoked by a JAXB provider’s
implementation during unmarshalling.
The print method converts a value of the
target Java datatype into its lexical representation of the XML schema
datatype. The print method is invoked by a JAXB provider’s
implementation during marshalling.
=== Usage
<javaType name=" _javaType_ "
{empty} [ xmlType=" _xmlType_ " ]
{empty} [ parseMethod="parseMethod" ]
[ printMethod="printMethod" ]>
The binding declaration can be used in one of
the following:
* a _<globalBindings>_ declaration.
* annotation element of one of the XML schema
elements specified in link:jaxb.html#a2079[See Customizable
Schema Elements].”
* in a <property> declaration. See
link:jaxb.html#a1783[See <property> Declaration].” This can be
used for customization at the point of reference to a simple type.
When used in a _<globalBindings>_
declaration, _<javaType>_ defines customization values with global
scope. When used in an annotation element of one of the schema elements
specified in link:jaxb.html#a2079[See Customizable Schema
Elements].” the customization values have component scope.
=== name
The _javaType_ , if specified, is the Java
datatype to which _xmlType_ is to be bound. Therefore, _javaType_ must
be a legal Java type name, which may include a package prefix. If the
package prefix is not present, then the Java type name must be one of
the Java built-in primitive types [JLS - Java Language Specification,
Second Edition, Section 4.2, “Primitive Types and Values”]. (For
example, “ _int_ ”) or a Java class in the unnamed package. If class
javaType declares a public constructor with following signature,
_javaType(java.lang.String)_ , _parseMethod_ attribute does not need to
be specified.
=== _xmlType_
The _xmlType_ , if specified, is the name of
the XML Schema datatype to which _javaType_ is to bound. If specified,
_xmlType_ must be a XML atomic datatype derived from restriction. The
use of the _xmlType_ is further constrained as follows.
The purpose of the _xmlType_ attribute is to
allow the global customization of a XML schema to Java datatype. Hence
_xmlType_ attribute is required when _<javaType>_ declaration’s parent
is _<globalBindings>_ . If absent, it must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].” Otherwise, the _xmlType_ attribute must not be present
since the XML datatype is determined from the XML schema element with
which the annotation element containing _<javaType>_ declaration or the
_<baseType>_ (containing the _<javaType>_ ) is associated. If present,
it must result in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations].”
Examples can be found in
link:jaxb.html#a2062[See Example: javaType Customization: Java
Built-in Type]” and link:jaxb.html#a2027[See Example: javaType
Customization: User Specified Parse Method]”
=== _parseMethod_
The parse method if specified, must be
applied during unmarshalling in order to convert a string from the input
document into a value of the target Java datatype. The parse method must
be invoked as follows:
* The parse method defaults to _new_ provided
_javaType_ is not a Java primitive type such as ( _"int"_ ). If
_javaType_ is a Java primitive type, then this must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].” Otherwise, the binding compiler must assume that the
target type is a class that defines a constructor as follows:
* _String_ as the first parameter of the
constructor.
To apply the conversion to a string it must
generate code that invokes this constructor, passing it the input
string.
* The parse method may be specified in the
form _ClassName.methodName,_ where the ClassName is a fully qualified
class name that includes the package name. A compiler must assume that
the class _ClassName_ exists and that it defines a static method named
_methodName_ that takes:
* _String_ as the first argument.
To apply the conversion to a string it must
generate code that invokes this method, passing it the input string.
* The parse method may be specified in the
form _methodName_ provided _javaType_ is not a Java primitive type (such
as _"int"_ ). If _javaType_ is Java primitive type, then this must
result in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations].” Otherwise,
the binding compiler must assume that _methodName_ is a method in the
class _javaType._ The binding compiler must therefore prefix the
_javaType_ to the _methodName_ and process _javaType._ _methodName_ as
specified in above.
The string passed to parse method can be any
lexical representation for _xmlType_ as specified in [XSD PART2].
If parseMethod attribute is not specified,
_xmlType_ is not a primitive or wrapper class and _javaType_ has an
accessible one argument constructor, where the argument is type
_java.lang.String_ , input text is parsed by invoking _new_ with a
_java.lang.String_ parameter.
=== _printMethod_
The print method if specified, must be
applied during marshalling in order to convert a value of the target
type into a lexical representation:
* The print method is specified in the form
_methodName_ provided _javaType_ is not a Java primitive type (such as
_"int"_ ). If _javaType_ is Java primitive type, then this must result
in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations].” Otherwise,
the compiler must assume that the target type is a class or an interface
that defines a zero-argument instance method named _methodName_ that
returns a _String_ . To apply the conversion it must generate code to
invoke this method upon an instance of the target Java datatype.
* If the print method is specified in the
form _ClassName.methodName_ then the compiler must assume that the class
_ClassName_ exists and that it defines a static method named
_methodName_ that returns a string that takes the following:
* the first parameter is the target Java
datatype.
To apply the conversion to a string it must
generate code that invokes this method, passing it a value of the target
Java datatype.
The lexical representation to which the value
of the target type is converted can be any lexical representation for
_xmlType_ as specified in [XSD PART2].
If _printMethod_ attribute is not specified
and _xmlType_ is not a primitive or wrapper class, _javaType.toString()_
is used as the default print method..
=== _DatatypeConverter_
Writing customized parse and print methods
can be difficult for a Java programmer. This requires a programmer to
understand the lexical representations of XML schema datatypes. To make
it easier, an interface, _DatatypeConverterInterface,_ and a class
_DatatypeConverter_ are defined to expose the parse and print methods of
a JAXB implementation. These can be invoked by user defined parse and
print methods. This shifts the burden of dealing with lexical spaces
back to the JAXB implementation.
The _DatatypeConverterInterface_ defines
parse and print methods for XML schema datatypes. There is one parse and
print method for each of XML schema datatype specified in
link:jaxb.html#a725[See Java Mapping for XML Schema Built-in
Types]. The interface is fully specified by the Javadoc specified in
_jakarta.xml.bind.DatatypeConverterInterface_ .
The _DatatypeConverter_ class defines a
static parse and print method corresponding to each parse and print
method respectively in the _DatatypeConverterInterface_ interface. The
property _jakarta.xml.bind.DatatypeConverter_ can be used to select the
name of a class that provides an implementation of the parse and print
methods. The name specified in the property must be a fully qualified
class name and must implement the interface _DatatypeConverterInterface_
. The class is fully specified by the Javadoc specified in
_jakarta.xml.bind.DatatypeConverter_ .
=== Usage
The following example demonstrates the use of
the _DatatypeConverter_ class for writing a customized parse and print
method.
=== [[a2027]]Example: javaType Customization: User Specified Parse Method
This example shows the binding of XML schema
type _"xs:date"_ is bound to a Java datatype _long_ using user specified
print and parse methods.
<jaxb:globalBindings> +
<jaxb:javaType name="long" xmlType="xs:date" +
parseMethod="pkg.MyDatatypeConverter.myParseDate" +
printMethod="pkg.MyDatatypeConverter.myPrintDate"/> +
</jaxb:javaType> +
</jaxb:globalBindings> +
package pkg; +
import jakarta.xml.bind.DatatypeConverter;
public class MyDatatypeConverter \{ +
public static long myParseDate(String s) \{
java.util.Calendar d =
DatatypeConverter.parse(s);
long result= cvtCalendarToLong(d) ; // user
defined method
return result; +
}
public static String myPrintDate(long l) \{
java.util.Calendar d = cvtLongToCalendar(l);
//user defined
return DatatypeConverter.print(d);
} +
}
The implementation of the print methods (
_parseDate_ and _printDate_ ) are provided by the user.
The customization is applied during the
processing of XML instance document. During unmarshalling, the JAXB
implementation invokes _myParseDate_ . If _myParseDate_ method throws a
_ParseException_ , then the JAXB implementation code catches the
exception, and generate a _parseConversionEvent_ .
=== Lexical And Value Space
[XSD PART 2] specifies both a value space and
a lexical space for an schema datatypes. There can be more than one
lexical representation for a given value.
Examples of multiple lexical representations
for a single value are:
* For boolean, the value _true_ has two
lexical representations _"true"_ and _"1"._
* For integer, the value _1_ has two lexical
representations _"1.0"_ and _"1"._
XSD PART 2 also specifies a canonical
representation for all XML schema atomic datatypes.
The requirements on the parse and print
methods are as follows:
* A JAXB implementation of a parse method in
_DatatypeConverterInterface_ must be capable of a processing all lexical
representations for a value as specified by [XSD PART 2]. This ensures
that an instance document containing a value in any lexical
representation specified by [XSD PART 2] can be marshalled.
* A JAXB implementation of a print method in
_DatatypeConverterInterface_ must convert a value into any lexical
representation of the XML schema datatype to which the parse method
applies, as specified by [XSD PART 2] and which is valid with respect to
the application’s schema.
*
=== Built-in Conversions
As a convenience to the user, this section
specifies some built-in conversions. A built-in conversion is one where
the parse and the print method may be omitted by a user. The built-in
conversions leverage the narrowing and widening conversions defined in
[JLS - Java Language Specification, Second Edition], Section 5.1.2,
“Widening Primitive Conversion” and Section 5.1.3, “Narrowing Primitive
Conversions.” For example:
<xs:simpleType name="foo" type="xs:long">
<xs:annotation><xs:appinfo>
<jaxb:javaType name="int"/>
</xs:appinfo></xs:annotation>
</xs:simpleType>
If the parse method is omitted, then a JAXB
implementation must perform the one of the following binding options:
. If _javaType_ is one of the following
primitive types or its corresponding wrapper class _byte, short, int,
long, float, double_ , bind _xmlType_ to its default Java datatype using
the parse method for the _xmlType_ defined in _DatatypeConverter_ . If
necessary, convert the default Java datatype for _xmlType_ to value of
type _javaType_ by a type cast.
. Else if default Java datatype defines a
public one-argument constructor that takes a _java.lang.String_ , use
_new_ with a _java.lang.String_ parameter for parsing.
. Else javaType(java.lang.String) does not
exist, this must result in an invalid binding customization as specified
in link:jaxb.html#a1544[See Invalid Customizations].
=== [[a2062]]Example: javaType Customization: Java Built-in Type
This example illustrates how to bind a XML
schema type to a Java type different from the default one.
XML Schema fragment:
<xs:element name="partNumber" type="xs:int"/>
Customization:
<jaxb:globalBindings>
....
<jaxb:javaType name="long"
xmlType="xs:int"/>
</jaxb:globalBindings>
Since a Java built-in is specified, a parse
or a print method need not be specified. A JAXB implementation uses the
parse and print methods defined in _DatatypeConverter_ class for
converting between lexical representations and values. A JAXB
implementation unmarshals an input value using the following methods:
int j =
(int)DataTypeConverter.parseLong(string);
=== Events
The parse method _parseMethod_ may fail,
since it is only defined on those strings that are valid representations
of target Java datatype values and it can be applied to arbitrary
strings. A parse method must indicate failure by throwing an exception
of whatever type is appropriate, though it should never throw a
_TypeConstraintException_ . A JAXB unmarshaller process must ensure that
an exception thrown by a parse method is caught and, if appropriate, a
_parseConversionEvent_ event is generated.
The print method _printMethod_ usually does
not fail. If it does, then the JAXB implementation must ensure that the
exception thrown by a print method is caught and a
_printConversionEvent_ is generated.
=== Customization Overrides
The _<javaType>_ overrides the default
binding of _xmlType_ to the Java datatype specified in
link:jaxb.html#a725[See Java Mapping for XML Schema Built-in
Types].
=== [[a2079]]Customizable Schema Elements
=== Simple Type Definition
A _<javaType>_ binding declaration is allowed
in the annotation element of the of a simple type definition. The
_javaType_ overrides the default binding of _xmlType_ to the Java
datatype specified in link:jaxb.html#a725[See Java Mapping for
XML Schema Built-in Types]. The customization values defined have
definition scope and thus covers all references to this simple type
definition.
If the simple type definition is mapped to a
schema-derived type, an _@XmlJavaTypeAdapter_ is generated on that
class. Annotation element _@XmlJavaTypeAdapter.value()_ is set to a
generated classlink:#a5379[28] that extends
_jakarta.xml.bind.annotation.adapter.XmlAdapter_ . The generated class’
_unmarshal_ method must call the <javaType> customization’s parse
method, which is specified in link:jaxb.html#a1981[See
<javaType> Declaration]. The generated class’ _marshal_ method must call
the <javaType> customization’s print method.
=== _GlobalBindings_
A _<javaType>_ binding declaration is allowed
as part of _<globalBindings>._ The _javaType_ overrides the default
binding of _xmlType_ to the Java datatype specified in
link:jaxb.html#a725[See Java Mapping for XML Schema Built-in
Types]. The customization values defined have global scope.
For each element or attribute declaration
that references an _xmlType_ that has a globalBindings _<javaType>_
customization specified for it, the corresponding JAXB property is
annotated with _@XmlJavaTypeAdapter_ .
=== _<property><baseType>_ declaration
A _<javaType>_ binding declaration is allowed
as part of _<baseType>_ in the _<property>_ binding declaration. The
_javaType_ overrides the default binding of _xmlType_ to the Java
datatype specified in link:jaxb.html#a725[See Java Mapping for
XML Schema Built-in Types]. Additional semantics are specified in
link:jaxb.html#a1801[See baseType]” also
apply.
The schema-derived JAXB property is annotated
with _@XmlJavaTypeAdapter_ as specified in
link:jaxb.html#a1801[See baseType]”.
=== [[a2090]] _<typesafeEnum>_ Declaration
This binding declaration allows the
customization of a binding of an XML schema element to its Java
representation as an enum type, Section 8.9 in [JLS3]. Only simple type
definitions with enumeration facets can be customized using this binding
declaration.
=== [[a2092]]Usage
<typesafeEnumClass> +
[ name = "enumClassName" ] +
[ map = “true” | “false” | “1” | “0” ] +
[ ref = "enumClassName" ] +
[ <typesafeEnumMember> ... </typesafeEnumMember> ]* +
[ <javadoc> enumClassJavadoc </javadoc> ] +
</typesafeEnumClass> +
+
<typesafeEnumMember name = "enumMemberName"> +
[ value = "enumMemberValue"] +
[ <javadoc> enumMemberJavadoc </javadoc> ] +
</typesafeEnumMember>
There are two binding declarations
_<typesafeEnumClass>_ and _<typesafeEnumMember>_ . The two binding
declarations allow the enumeration members of an enumeration class and
enumeration class itself to be customized independently.
The < _typesafeEnumClass>_ declaration
defines the following customization values:
* _name_ defines the customization value
_enumClassName_ , if specified. _enumClassName_ must be a legal Java
Identifier; it must not have a package prefix. +
+
For an anonymous simple type, the _name_ attribute must be present. If
absent, it must result in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations].”
* _map_ determines if the simple type
definition should be bound to an enum type. When _map_ ’s value is
_false_ , then the simple type definition must not be bound to an enum
type. _map_ defaults to _true_ .
* _ref_ if specified, is the name of the
enum class that is provided outside the schema compiler. This
customization causes a schema compiler to refer to this external enum,
as opposed to generate a definition. It must include the complete
package name. This attribute is mutually exclusive with the _className_
attribute and the _map_ attribute.
* _<javadoc>_ element, if specified
customizes the Javadoc for the enumeration class. _<_ _javadoc>_ defines
the customization value _enumClassjavadoc_ if specified as described in
link:jaxb.html#a2142[See <javadoc> Declaration].”
* Zero or more _<typesafeEnumMember>_
declarations. The customization values are as defined as specified by
the _<typesafeEnumMember>_ declaration.
The _<typesafeEnumMember>_ declaration
defines the following customization values:
* _name_ must always be specified and
defines a customization value _enumMemberName_ . _enumMemberName_ must
be a legal Java identifier.
* _value_ defines a customization value
_enumMemberValue_ , if specified. _enumMemberValue_ must be the
enumeration value specified in the source schema. The usage of _value_
is further constrained as specified in link:jaxb.html#a2106[See
value Attribute].”
* _<javadoc>_ if specified, customizes the
Javadoc for the enumeration constant. _<javadoc>_ defines a
customization value _enumMemberjavadoc_ if specified as described in
link:jaxb.html#a2142[See <javadoc> Declaration].”
For inline annotation, the
_<typesafeEnumClass>_ must be specified in the annotation element of the
< _simpleType_ > element. The _<typesafeEnumMember>_ must be specified
in the annotation element of the enumeration member. This allows the
enumeration member to be customized independently from the enumeration
class.
=== _value_ [[a2106]] Attribute
The purpose of the _value_ attribute is to
support customization of an enumeration value using an external binding
syntax. When the _<typesafeEnumMember>_ is used in an inline annotation,
the enumeration value being customized can be identified by the
annotation element with which it is associated. However, when an
external binding declaration is used, while possible, it is not
desirable to use XPath to identify an enumeration value.
So when customizing using external binding
syntax, the _value_ attribute must be provided. This serves as a key to
identify the enumeration value to which the _<typesafeEnumMember>_
applies. It’s use is therefore further constrained as follows:
* When _<typesafeEnumMember>_ is specified in
the annotation element of the enumeration member or when XPath refers
directly to a single enumeration facet, then the value attribute must be
absent. If present, it must result in must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].”
* When _<typesafeEnumMember>_ is scoped to
the _typesafeEnumClass_ declaration, the value attribute must be
present. If absent, it must result in must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].” The enumMemberValue must be used to identify the
enumeration member to which the _<typesafeEnumMember>_ applies.
An example of external binding syntax can be
found in link:jaxb.html#a2134[See Example 2: typesafeEnum
Customization: External Binding Declaration].”
=== Inline Annotations
There are two ways to customize an
enumeration class:
* split inline annotation
* combined inline annotation
In split inline annotation, the enumeration
value and the enumeration class are customized separately i.e. the
_<typesafeEnumMember>_ is used independently not as a child element of
_<typesafeEnumClass>._ An example of this is shown in
link:jaxb.html#a2129[See Example 1: typesafeEnum Customization:
Split Inline Annotation].”
In combined inline annotation, the
enumeration value and the enumeration class are customized together i.e.
the _<typesafeEnumMember>_ is used as a child element of
_<typesafeEnumClass>._ This is similar to the customization used in
external binding declaration. In this case the _value_ attribute must be
present in the _<typesafeEnumMember>_ for reasons noted in
link:jaxb.html#a2106[See value Attribute].” An example of this
customization is shown in link:jaxb.html#a2138[See Example 3:
typesafeEnum Customization: Combined Inline Annotation].”
=== Customization Overrides
When binding a schema type definition’s Java
representation to an enum type, the following customization values
override the defaults specified in Chapter 5. It is specified in a
common section here and referenced from link:jaxb.html#a1857[See
Customizable Schema Elements].”
* name: If enumClassName is defined, then the
name obtained by mapping enumClassName as specified in
link:jaxb.html#a1608[See Customized Name Mapping].”
* package name: The name obtained by
inheriting _packgeName_ from a scope that covers this schema element and
mapping packageName as specified in link:jaxb.html#a1608[See
Customized Name Mapping].”
* enumclass javadoc: _enumClassJavaDoc_ if
defined, customizes the _class/interface section (_
link:jaxb.html#a2145[See Javadoc Sections]”) for the enumeration
class, as specified in link:jaxb.html#a2163[See Javadoc
Customization].”
* enum constant set: Each member of the set
is computed as follows:
* name: If enumMemberName is defined, the
name obtained by mapping enumMemberName as specified in
link:jaxb.html#a1608[See Customized Name Mapping].”
* javadoc: _enumMemberJavaDoc_ if defined,
customizes the _field section (_ link:jaxb.html#a2145[See
Javadoc Sections]” ) for the enumeration class, as specified in
link:jaxb.html#a2163[See Javadoc Customization].”
=== [[a2126]]Customizable Schema Elements
Any XML Schema simple type which has an
enumeration facet can be customized with _<jaxb:typesafeEnumClass>_
declaration with the following exception. If the simple type definition
derives from _xs:QName. xs:NOTATIION, xs:base64Binary, xs:hexBinary,
xs:date, xs:time, xs:dateTime, xs:duration, xs:gDay, xs:gMonth,
xs:gYear, xs:gMonthDay, xs:gYearMonth, xs:IDREF, xs:ID_ , it must result
in an invalid customization as specified in
link:jaxb.html#a1544[See Invalid Customizations].”. Since most
of these Xml datatypes bind to a mutable Java type, instances of these
Java types are not sufficient to be an immutable value of an enum
constant.
*
=== [[a2129]]Example 1: typesafeEnum Customization: Split Inline Annotation
XML Schema fragment:
<xs:simpleType name="USState"> +
<xs:annotation><xs:appinfo> +
<jaxb:typesafeEnumClass name="USStateAbbr"/> +
</xs:appinfo></xs:annotation> +
<xs:restriction base="xs:NCName"> +
<xs:enumeration value="AK"> +
<xs:annotation><xs:appinfo> +
<jaxb:typesafeEnumMember name="STATE_AK"/> +
</xs:appinfo></xs:annotation> +
</xs:enumeration> +
<xs:enumeration value="AL"> +
<xs:annotation><xs:appinfo> +
<jaxb:typesafeEnumMember name="STATE_AL"/> +
</xs:appinfo></xs:annotation> +
</xs:enumeration> +
</xs:restriction> +
</xs:simpleType>
Customized derived code:
public enum USStateAbbr \{ +
STATE_AL, STATE_AK; +
public String value() \{ return name(); } +
public static USStateAbbr fromValue(String value) \{ ... } +
};
=== [[a2134]]Example 2: typesafeEnum Customization: External Binding Declaration
The following example shows how to customize
the above XML schema fragment using an external binding syntax.
<jaxb:typesafeEnumClass name="USStateAbbr"> +
<jaxb:typesafeEnumMember name="STATE_AK" value="AK"> +
<jaxb:typesafeEnumMember name="STATE_AL" value="AL"/> +
</jaxb:typesafeEnumClass>
The attribute _value_ must be specified for
_<typesafeEnumMember>_ . This identifies the enumeration member to which
_<typesafeEnumMember>_ applies.
=== [[a2138]]Example 3: typesafeEnum Customization: Combined Inline Annotation
The following example shows how to customize
the above XML schema fragment using inline annotation which does not
split the external binding syntax.
<xs:simpleType name="USState"> +
<xs:annotation><xs:appinfo> +
<jaxb:typesafeEnumClass name="USStateAbbr"> +
<jaxb:typesafeEnumMember name="STATE_AK" value="AK"/> +
<jaxb:typesafeEnumMember name="STATE_AL" value="AL"/> +
</jaxb:typesafeEnumClass> +
</xs:appinfo></xs:annotation> +
<xs:restriction base="xs:NCName"> +
<xs:enumeration value="AK"/> +
<xs:enumeration value="AL"/> +
</xs:restriction> +
</xs:simpleType>
The attribute value must be specified for
_typesafeEnumMember_ . This identifies the enumeration member to which
the binding declaration applies.
=== _<javadoc>_ [[a2142]] Declaration
The _<javadoc>_ declaration allows the
customization of a javadoc that is generated when an XML schema
component is bound to its Java representation.
This binding declaration is not a global XML
element. Hence it can only be used as a local element within the content
model of another binding declaration. The binding declaration in which
it is used determines the section of the Javadoc that is customized.
=== [[a2145]]Javadoc Sections
The terminology used for the javadoc sections
is derived from “Requirements for Writing Java API Specifications” which
can be found online at http:
_//java.sun.com/j2se/javadoc/writingapispecs/index.html._
The following sections are defined for the
purposes for customization:
* package section (corresponds to package
specification)
* class/interface section (corresponds to
class/interface specification)
* method section (corresponds to method
specification)
* field section (corresponds to field
specification)
=== Usage
Note that the text content of a _<javadoc>_
element must use _CDATA_ or _&lt;_ to escape embedded HTML tags.
<javadoc>
Contents in &lt;b>Javadoc&lt;\b> format.
</javadoc>
or
<javadoc>
<<![CDATA[
Contents in <b>Javadoc<\b> format
]]>
</javadoc>
=== [[a2163]]Javadoc Customization
The Javadoc must be generated from the
_<javadoc>_ element if specified. The Javadoc section depends upon where
_<javadoc>_ element is used. JAXB providers may generate additional
provider specific Javadoc information (for example, contents of the
_<xs:documentation>_ element).
=== _<dom>_ [[a2165]] Declaration
The _<dom>_ customization binds an XML Schema
component to DOM rather than to a strongly typed Java representation.
Specifically, JAXB bindings for mixed content and wildcard result in a
hybrid mixture of strongly typed Java instances with DOM nodes or
java.lang.String, representing text info. These mixed bindings might be
more easily processed solely as one form, namely as an XML fragment
represented as DOM. This customization also meets a JAX-WS 2.0
databinding requirement from link:jaxb.html#a179[See Disabling
Databinding]”.
=== Usage
The syntax for the customization is the
following:
<dom [ [type= "w3c" |
_otherDomRepresentations_ ] />
You can use the optional type attribute to
specify the type of DOM. By default, it is W3C DOM.
=== Customizable Schema Elements
This customization can be attached to the
following XML Schema components:
* Element declaration ( _<xs:element>_ )
* Type definition ( _<xs:complexType>_ and
_<xs:simpleType>_ )
* Wildcard ( _<xs:any>_ )
* Model groups ( _<xs:choice>_ _,_ _<xs:all>_
_,_ _<xs:sequence>_ )
* Model group definition ( _<xs:group>_ )
* Particle
For all of the above cases, the Java
representation of the DOM element is an instance of the Element class
for the specified DOM representation. For example, W3C DOM element is
bound to _org.w3c.dom.Element_ .
Special Case Handling of DOM customization on
a:
* _type definition_ - it is semantically
equivalent to placing the dom customization on each element declaration
referencing that type definition.
* _global element declaration_ - it is
semantically equivalent to placing the dom customization on each element
declaration referencing, via _@ref_ , the global element declaration.
The dom customization on the global element declaration does not cause
that element to be unmarshalled as DOM when it is the root element of an
XML document nor when the element is part of a wildcard content JAXB
property.
* _mixed content_ - if an XML schema
component is annotated with a _dom_ customization and that XML schema
component can contain character data information due to its parent
complex type definition being defined with mixed content, character data
information is handled as specified in link:jaxb.html#a1369[See
Bind mixed content]”.
The dom customization allows one to disable
databinding and process a part of a document using other technologies
that require “raw” XML.
=== Examples
=== Wildcard Binding Example
A wildcard is mapped to a List of
_org.w3c.dom.Element_ . Each element that matches to the wildcard will
be turned into a DOM tree.
<xs:complexType name=”foo”> +
<xs:sequence> +
<xs:any maxOccurs="unbounded" processContents="lax"> +
_<xs:annotation><xs:appinfo> +
<jaxb:dom/> +
</xs:appinfo></xs:annotation> +
_ </xs:any> +
</xs:sequence> +
</xs:complexType>
+
import org.w3c.dom.Element; +
public class Foo \{ +
@XmlAnyElement(lax=”false”) +
List<Element> getContent()\{...} +
}
=== Wildcard and Mixed Content Binding Example
If the complexType definition above is
defined to have mixed content, due to element _[complexType]_ __ having
attribute _@mixed=”true”_ , the JAXB binding is:
import org.w3c.dom.Element; +
public class Foo \{ +
/* Element content is represented _org.w3c.dom.Element_ . +
* Character data information is represented as instances of +
* _java.lang.String_ . */ +
@XmlMixed +
@XmlAnyElement(lax=”false”) +
List<Object> getContent()\{...} +
}
=== _<inlineBinaryData>_ [[a2193]] Declaration
The _<inlineBinaryData>_ customization
provides declarative control over the optimization for binary data
described in link:jaxb.html#a5109[See Appendix],
link:jaxb.html#a5110[See Enhanced Binary Data Handling].
=== Usage
The syntax for the customization is the
following:
<inlineBinaryData/>
This customization disables considering the
binary data optimization for a schema component containing binary data.
This customization can be attached to the
following XML Schema components:
* Element declaration ( _<xs:element>_ ) with
binary data or
* Type definition ( _<xs:complexType>_ and
_<xs:simpleType>_ ) deriving from binary datatype
When a schema component that binds to a JAXB
property is customized with <inlineBinaryData>, its schema-derived JAXB
property is annotated with _@XmlInlineBinaryData_ . When a type
definition is customized with <inlineBinaryData>, its schema-derived
class is annotated with program annotation _@XmlInlineBinaryData_ .
=== _<factoryMethod>_ Declaration
The _<factoryMethod>_ customization provides
declarative control over an element or type factory method name
generated in a package’s _ObjectFactory_ class introduced in
link:jaxb.html#a482[See Java Package].”. This customization is
useful to resolve name collisions between factory methods in the
schema-derived _ObjectFactory_ class.
=== Usage
The syntax for the customization is the
following:
<factoryMethod
name=”BaseForFactoryMethodName”/>
The customization value defined is:
* _name -_ each character of name must be a
valid part of a Java identifier as determined by
_java.lang.Character.isJavaIdentifierPart()._
The name of the factory method is generated
by concatenating the following components:
* The string constant _create_
* _@name_ ’s value
=== Usage Constraints
The usage constraints on _<factoryMethod>_
are specified below. Any constraint violation must result in an invalid
customization as specified in link:jaxb.html#a1544[See Invalid
Customizations].” The usage constraints are:
. _<factoryMethod>_ is only allowed to
annotate an element declaration or a type definition.
Note that this customization does not require
a factory method to be generated, it simply provides a factory method
name if a factory method is to be generated for the annotated element
declaration or type definition. Section 6 and 7 specifies when a factory
method is generated for an element declarations or type definitions.
=== [[a2217]]Annotation Restrictions
[XSD PART 1] allows an annotation element to
be specified for most elements but is ambiguous in some cases. The
ambiguity and the way they are addressed are described here.
The source of ambiguity is related to the
specification of an annotation element for a reference to a schema
element using the “ref” attribute. This arises in three cases:
* A local attribute references a global
attribute declaration using the “ref” attribute.
* A local element in a particle references a
global element declaration using the “ref” attribute.
* A model group in a particle references a
model group definition using the “ref” attribute.
For example in the following schema fragment
(for brevity, the declaration of the global element “Name” and “Address”
has been omitted).
_<xs:element name = "Customer">_
_<xs:complexType>_
_<xs:element ref = "Name"/>_
_<xs:element ref = "Address" />_
_</xs:complexType>_
_</xs:element>_
XML Schema spec is ambiguous on whether an
annotation element can be specified at the reference to the “Name”
element.
The restrictions on annotation elements has
been submitted as an issue to the W3C Schema Working Group along with
JAXB technology requirements (which is that annotations should be
allowed anywhere). Pending a resolution, the semantics of annotation
elements where the XML spec is unclear are assumed as specified as
follows.
This specification assumes that an annotation
element can be specified in each of the three cases outlined above.
Furthermore, an annotation element is assumed to be associated with the
abstract schema component as follows:
* The annotation element on an attribute ref
is associated with \{Attribute Use}
* The annotation element on a model group ref
or an element reference is associated with the \{particle}.
== CHAPTER 8 -
[[a2236]]Java Types To XML
=== Introduction
This chapter specifies the mapping from
program elements to XML Schema. The mapping includes a default as well
as a customized mapping.
=== Overview
This section is non normative and provides a
high level view of Java to XML Schema mapping targeted towards both JAXB
application developers and JAXB implementation vendors.
=== Mapping Scope
The mapping covers program elements commonly
used in the composition of a data model for an application: package,
field, property and types (classes and enum construct). Additionally,
the mapping scope also covers mapping annotations used to annotate
schema derived code.
In so far as possible, a program element is
mapped to an equivalent XML Schema construct in an intuitive manner.
Thus,
* Package maps to a XML target namespace. A
package provides a naming context for types. A XML target namespace
provides a naming context for schema components such as elements, type
definitions.
* Type maps to a schema type. A value type is
a data container for values; e.g. a value class contains values
represented by it’s properties and fields. A schema type is a datatype,
an instance of which (e.g. element) acts as a data container for values
represented by schema components within a schema type’s content model
(e.g. element, attributes, etc.). Thus a type maps naturally to a schema
type. For e.g.,
* class typically maps to a complex type
definition
* java primitive types and wrapper classes map
to XML Schema simple type definition.
* Field or property maps to an element or an
attribute contained within the complex type to which a type is mapped.
* Enum type maps to a simple schema type
constrained by enumeration facets.
The input to the mapping process is one or
more sets of packages or classes. A package or a class is mapped and
recursively, fields, properties and types contained with it. The mapping
is customizable.
=== Mapping Annotations
Mapping annotationsThe mapping of program
elements to XML Schema construct can be customized using mapping
annotations, program annotations based on JSR 175 program annotation
facility. Mapping annotations are used for:
* customizing the Java to XML schema mapping.
* annotating schema derived code.
* control over optimized binary data encoding.
The mapping annotations are described in the
_jakarta.xml.bind.annotation_ and _jakarta.xml.bind.annotation.adapters_
packages.
Retention Policy The retention policy of all
mapping annotations is RetentionPolicy.RUNTIME. This policy allows
introspection of mapping annotations at runtime. Introspection can be
used by JAXB binding framework to marshal/unmarshal an object graph to
XML representation or to customize the mapping of program elements to
XML Schema constructs. This policy also allows a JAXB vendor
implementation to generate a schema from a program element’s compiled
form rather than its source.
=== XML Name Derivation
Mapped program element is a program element
that has been mapped to an XML Schema construct. It is possible to use
_@XmlTransient_ annotation type to prevent the mapping of a program
element.
XML Names An XML name may be needed for the
schema components for a mapped program element, for e.g. element name.
XML names are usually derived from a program element name, for e.g.
property, field, class name etc.But they can be customized using mapping
annotation. When an XML name is derived from a property name, bean de
capitalization rules are used. If a Java Identifier is not a legal XML
name, then a legal XML name can be assigned using an annotation element
(e.g. _@XmlType(name=”foo”)_ ).
=== Fields and Properties
XML global element Fields and properties
typically map to local elements within a complex type for a class. But a
well formed XML document begins with a root element (a global element in
the corresponding schema). The _@XmlRootElement_ annotation can be used
to associate a global element with a class or an enum type.
Null Value and Nillable Element A null value
for a type mapped to an XML Schema element in two ways: absence of an
element or an nillable element. The mapping annotation for an element
allows either mapping.
=== Type Mapping
Legacy applications One of the primary use
cases for Java language to XML Schema mapping is to allow an existing
application to be exported as a web service. In many cases, the existing
applications are legacy applications consisting of classes that follow
different class designs. The annotations and default mapping are
designed to enable such classes to be mapped to schema with minimal
changes to existing code. See link:jaxb.html#a3676[See Default
Mapping] for default mapping.
Class A class usually maps to a complex type.
However, using _@XmlValue_ annotation, a class can also be mapped to a
simple type (to hold a simple value) or a complexType with simpleContent
(to hold a simple value and attributes). The _@XmlType_ annotation can
be used to customize the mapping of a class. For example, it can be used
to map a class to an anonymous type or to control the ordering of
properties and/or fields. Properties and fields are unordered; but they
can be mapped to a content model that is ordered (e.g. xs:sequence) or
unordered content model (xs:all).
Class Designs A class with a public or
protected no-arg constructor can be mapped. If a class has a static
zero-arg factory method, then the factory method can be specified using
the annotation element _@XmlType.factoryMethod()_ and
_@XmlType.factoryClass()_ .
Ordering of Properties/fields: The ordering of
properties and fields can be customized in one of two ways: at the
package level using @XmlAccessorOrder or using _@XmlType.propOrder()_ at
the class level.
Class Hierarchy Mapping Class hierarchy
typically maps to a type derivation hierarchy. The _@XmlType_ and
_@XmlValue_ annotations together provide support mapping class hierarchy
to schema type hierarchy where XML Schema complex type derives by
extension from either another complex type or a simple type.
Supported Collection Types Typed collections
and untyped collections are mapped. Mapped collection types are: arrays,
indexed properties and parametric types. Mapped untyped collection are:
_java.util.List_ , _java.util.Set_ and _java.util.HashMap_ . Of these,
_java.util.HashMap_ does not map naturally to a XML Schema construct.
For example, _HashMap_ can have different XML serialized forms which
differ in trade-offs made between memory and speed or specificity and
generality. The XML serialization form can be customized using
_@XmlJavaTypeAdapter_ (link:jaxb.html#a2278[See Adapter]”).
Collection serialized forms A collection type
can be mapped to a XML Schema complex type and collection item is mapped
to local element within it. Alternately, a parameterized collection
(e.g. List<Integer>) can be mapped to a simple schema type that derives
by list.
When a collection type is mapped to a XML
Schema complex type, the mapping is designed to support two forms of
serialization shown below.
//Example: code fragment +
int[] names; +
+
// XML Serialization Form 1 (Unwrapped collection) +
// Element name is derived from property or field name +
<names> ... </names> +
<names> ... </names> +
... +
+
// XML Serialization Form 2 ( Wrapped collection ) +
// Element name of wrapper is derived from property or field name +
// Element name of each item in collection is also derived from
// property name +
<names> +
<names> value-of-item </names> +
<names> value-of-item </names> +
.... +
</names>
The two serialized XML forms allow a null
collection to be represented either by absence or presence of an element
with a nillable attribute. The _@XmlElementWrapper_ annotation on the
property or field is used to customize the schema corresponding to the
above XML serialization forms.
A parameterized collection (e.g.
List<Integer>) can also be mapped to simple schema that derives by list
using _@XmlList_ annotation. For e.g. the serialized XML form is: “1 2 3
“.
=== [[a2278]]Adapter
A type may not map naturally to a XML
representation (see Supported Collection Types above). As another
example, a single instance of a type may have different on wire XML
serialization forms.
Adapter approach defines a portable
customization mechanism for applications exemplified above. The
mechanism provides a way to adapt a bound type, a Java type used to
process XML content, to value type, mapped to an XML representation or
vice versa. It is the value type that is used for marshalling and
unmarshalling. Use of this approach involves two steps:
* provide an adapter class that extends the
abstract class _@jakarta.xml.bind.annotation.adapters.XmlAdapter_ that
defines two methods _unmarshal()_ and _marshal()_ . The methods are
invoked by JAXB vendor implementation during unmarshalling and
marshaling respectively to adapt between bound and value types.
* specify the adapter class using the
_@XmlJavaTypeAdapter_ annotation.
=== Referential Integrity
Preserving referential integrity of an object
graph across XML serialization followed by a XML de serialization,
requires an object reference to be marshalled by reference or
containment appropriately. Possible strategies include:
* marshal all references to a given object by
reference.
* marshal the first reference to an object by
containment and subsequent references to the same object by reference.
Depending on the strategy, the schema to which
program element is mapped also varies accordingly.
Two annotations _@XmlID_ and _@XmlIDREF_
provide the mechanism which can be used together to map program element
by reference or containment. This places the burden of preserving
referential integrity on a developer. On the other hand, the ability to
customize the mapping is useful since it can result in mapping of
program elements to a schema that defines a document structure more
meaningfully to an application than a default derived schema.
=== Property/Field Name Collision
A XML name collision can arise when the
property name obtained by bean de capitalization and the name of a field
map to a same schema component. For example
public int item;
pubilc int getItem();
public void setItem(int val);
The name collision occurs because the property
name, bean de capitalization, and the name of the public field are both
the same i.e. _item._ In the case, where the property and the public
field refer to the same field, the _@XmlTransient_ can be used to
resolve the name collision by preventing the mapping of either the
public field or the property.
=== Naming Conventions
Any source and schema fragments and examples
shown in this chapter are meant to be illustrative rather than
normative.
* _@XmlAttribute_ denotes both a program
annotation type as well a specific use of annotation type.
* The prefix _xs:_ is used to refer to schema
components in W3C XML Schema namespace.
* The prefix _ref:_ is used to refer to schema
components in the namespace _“http://ws-i.org/profiles/basic/1.1/xsd”_
*
=== Constraint Violations
For the purpose of mapping and constraint
checking, if a program element is not annotated explicitly, and there is
a default mapping annotation defined for that element, it must be
applied first before performing any constraint checks or mapping. This
is assumed in the normative mapping tables shown below.
The mapping of program elements to XML Schema
constructs is subject to mapping constraints, specified elsewhere in
this chapter. The mapping constraints must be enforced by the
_jakarta.xml.bind.annotation.JAXBContext.newInstance(..)_ method. Any
cycles resulting from a combination of annotations or default mapping
must be detected in
_jakarta.xml.bind.annotation.JAXBContext.newInstance(..)_ method and also
constitutes a constraint violation. A _jakarta.xml.bind.JAXBException_ or
(its subclass, which can be provider specific) must be thrown upon a
constraint violation.
A JAXB Provider must support the schema
generation at runtime. See
_jakarta.xml.bind.JAXBContext.generateSchema(..)_ for more information.
=== Type Mapping
This section specifies the mapping of Java
types to XML Schema.
=== Java Primitive types
The default mapping of Java types (and their
wrapper classes) specified in table link:jaxb.html#a2310[See
Mapping: Java Primitive types to Schema Types] must be supported.
=== [[a2310]]Mapping: Java Primitive types to Schema Types
Java Primitive Type
XML data type
boolean
xs:boolean
byte
xs:byte
short
xs:short
int
xs:int
long
xs:long
float
xs:float
double
xs:double
=== Java Standard Classes
The default mapping of Java classes specified
in link:jaxb.html#a2329[See Mapping of Standard Java classes]
must be supported.
=== [[a2329]]Mapping of Standard Java classes
Java Class
XML data type
java.lang.String
xs:string
java.math.BigInteger
xs:integer
java.math.BigDecimal
xs:decimal
java.util.Calendar
xs:dateTime
java.util.Date
xs:dateTime
javax.xml.namespace.QName
xs:QName
java.net.URI
xs:string
javax.xml.datatype.XMLGregorianCalendar
xs:anySimpleType
javax.xml.datatype.Duration
xs:duration
java.lang.Object
xs:anyType
java.awt.Image
xs:base64Binary
javax.activation.DataHandler
xs:base64Binary
javax.xml.transform.Source
xs:base64Binary
java.util.UUID
xs:string
*
A byte[] must map to xs:base64Binary by
default.
=== Generics
=== Type Variable
The following grammar is from [JLS], Section
4.4, “Type Variables”.
_TypeParameter: +
TypeVariable TypeBoundopt_
_TypeBound: +
extends ClassOrInterfaceType AdditionalBoundListopt_
A type variable without a Typebound must be
mapped to xs:anyType.
A type variable with a TypeBound must map to
the schema type to which ClassOrInterfaceType is mapped; the mapping of
ClassOrInterface is subject to the mapping constraints specified in
other sections in this chapter.
<!-- code fragment
public class Shape <T> \{
public T xshape;
public Shape() \{};
public Shape(T f) \{
xshape = f;
}
}
<!-- XML Schema
<xs:complexType name="shape">
<xs:sequence>
<xs:element name="xshape" type="xs:anyType"
minOccurs="0"/>
</xs:sequence>
</xs:complexType>
=== [[a2386]]Type Arguments and Wildcards
The following grammar is from [JLS], Section
4.5.1, “Type Arguments and Wildcards”.
TypeArguments:
<ActualTypeArgumentList>
ActualTypeArgumentList:
ActualTypeArgument
ActualTypeArgumentList, ActualTypeArgument
ActualTypeArgument:
ReferenceType
Wildcard
Wildcard:
?WildcardBounds
WildcardBounds:
extends ReferenceType
super ReferenceType
A wildcard without a WildcardBounds must map
to schema type xs:anyType.
A wildcard with a WildcardBounds whose super
type is ReferenceType must map to schema type xs:anyType.
A wildcard with a WildcardBounds that extends
a ReferenceType must map to the schema type to which the ReferenceType
is mapped; this mapping is subject to the mapping constraints specified
in other sections in this chapter and is determined by the annotations
as specified in the mapping tables in the chapter. For example:
/** EXAMPLE : WildcarType Mapping
// Code fragment
public class Shape \{...}
public class Rectangle extends Shape \{...}
public class Circle extends Shape \{...}
public class Foo \{
public java.util.List<? extends Shape>
shapes;
}
<-- XML Schema fragment
<xs:complexType name="shape">
...
</xs:complexType>
<xs:complexType name="circle">
<xs:complexContent>
<xs:extension base="shape">
...
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="rectangle">
<xs:complexContent>
<xs:extension base="shape">
...
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="foo">
<xs:sequence>
<xs:element name="shapes" type="shape"
nillable="true"
maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
=== Collections
The following collection must be supported:
* _java.util.Map_ and its subtypes (e.g.
java.util.HashMap)
* _java.util.Collection_ and it’s subtypes
(e.g. java.util.List)
The mapping of collection depends upon the
annotations on the program elements and is specified in the mapping
tables. This specification uses a collection type to be one of
_java.util.Collection_ (or a subtype derived from it) , an array or an
JavaBean index property.
=== Java Package
_@XmlSchema_ is used in the mapping of
package to an XML target namespace.
=== [[a2456]]@XmlSchema
=== Synopsis
public enum XmlNsForm \{UNQUALIFIED,
QUALIFIED, UNSET}
@Retention(RUNTIME) @Target(\{})
public @interface XmlNs \{
@Retention(RUNTIME) @Target(\{PACKAGE})
public @interface XmlSchema \{
XmlNs[] xmlns() default \{};
String namespace() default "";
String location() default "";
XmlNsForm elementFormDefault() default
XmlNsForm.UNSET;
XmlNsForm attributeFormDefault() default
XmlNsForm.UNSET;
}
=== Mapping
If _location()_ is “”, a package annotated
with _@XmlSchema_ must be mapped as specified in
link:jaxb.html#a2476[See Mapping: Package to XML target
namespace]. Otherwise a package will not produce any schema document.
*
*
=== Mapping: Package to [[a2476]]XML target namespace
_targetNamespace_
if _@XmlSchema.namespace()_ is __ "" _,_ then
_absent;_
otherwise @XmlSchema.namespace()
_elementFormDefault_
if the value of
_@XmlSchema.elementFormDefault()_ is _@XmlNsForm.UNSET,_ then _absent;_
otherwise, the value of
_@XmlSchema.elementFormDefault()_
_attributeFormDefault_
if the value of
_@XmlSchema.attributeFormDefault()_ is _@XmlNsForm.UNSET,_ then
_absent;_
otherwise, the value of
_@XmlSchema.attributeFormDefault()_
_Namespace prefixes_
if _@XmlSchema.xmlns()_ is \{} then
implementation defined;
otherwise _@XmlSchema.xmlns()_
=== @XmlAccessorType
This annotation allows control over default
serialization of fields and properties.
=== Synopsis
@Inherited @Retention(RUNTIME)
@Target(\{PACKAGE, TYPE})
public @interface XmlAccessorType \{
XmlAccessType value() default
XmlAccessType.PUBLIC_MEMBER;
}
public enum XmlAccessType \{ NONE, PROPERTY,
FIELD, PUBLIC_MEMBER}
=== Mapping
The following mapping constraints must be
enforced:
This annotation can be used only with the
following other annotations: _@XmlType, @XmlRootElement_ ,
_@XmlAccessorOrder, @XmlSchema, @XmlSchemaType, @XmlSchemaTypes,
@XmlJavaTypeAdapters._ It can also be used with the following
annotations at the package level: _@ XmlJavaTypeAdapter_ .
See link:jaxb.html#a3676[See Default
Mapping]”.
=== [[a2506]]@XmlAccessorOrder
This annotation allows control over the
default ordering of properties and fields that are mapped to XML
elements. Properties and fields mapped to XML attributes are not
impacted by this annotation since XML attributes are unordered.
=== Synopsis
@Inhertited @Retention(RUNTIME)
@Target(\{PACKAGE, TYPE})
public @interface XmlAccessorOrder \{
XmlAccessOrder value() default
XmlAccessOrder.UNDEFINED;
}
public enum XmlAccessOrder \{ UNDEFINED,
ALPHABETICAL}
=== Mapping
The following mapping constraints must be
enforced:
. This annotation can be
used only with the following other annotations: _@XmlType,
@XmlRootElement_ , _@XmlAccessorType, @XmlSchema, @XmlSchemaType,
@XmlSchemaTypes, @XmlJavaTypeAdapters._ It can also be used with the
following annotations at the package level: _@ XmlJavaTypeAdapter_ .
If the value of _@XmlAccessorOrder.value()_ is
_XmlAccessOrder.ALHPHABETICAL_ , then the default ordering of
fields/properties is lexicographic order as determined by
_java.lang.String.CompareTo((String anotherString)_ .
If the _@XmlAccessorOrder.value()_ is
_XmlAccessOrder.UNDEFINED_ , then the default ordering of
fields/properties is unspecified.
=== [[a2520]]@XmlSchemaType
This annotation allows a customized mapping to
a XML Schema built in type. This is useful where a Java type can map to
more than one schema built in types. An example is
_XMLGregorianCalendar_ which can represent one of the eight schema
built-in types.
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD,
PACKAGE})
public @interface XmlSchemaType \{
String name();
String namespace() default
"http://www.w3.org/2001/XMLSchema";
Class type() default DEFAULT.class;
static final class DEFAULT \{}
}
=== Mapping
The following mapping constraints must be
enforced:
* name() must be an atomic simple type schema
type (or a type that derives from it) to which the type of the property
or field can be mapped from XML Schema -> Java as specified in Section
6.2.2, “Atomic Datatype”. Example
// @XmlSchemaType can specify any one of the
eight calendar types
// that map to XMLGregorianCalendar.
@XmlSchemaType(name=”date”)
XMLGregorianCalendar foo;
* If the annotation is used as a package
level annotation or within _@XmlSchemaTypes_ , value of
_@XmlSchemaType.type()_ must be specified and must be the Java type that
is being customized.
* If the annotation is used on a field or a
method, then value of type() must be DEFAULT.class.
* This annotation can only be used with the
following other annotations: _@XmlElement, @XmlAttribute,
@XmlJavaTypeAdapter, @XmlJavaTypeAdapters._
package:
When this annotation is used at the package
level, the mapping applies to references to _@XmlSchemaType.type()_ as
specified below. For clarity, the following code example is used along
with normative text.
// Example: change the default mapping at
package level
package foo;
@jakarta.xml.bind.annotation.XmlSchemaType
(name="date",
type=javax.xml.datatype.XMLGregorianCalendar.class)
A _@XmlSchemaType_ that is specified as a
package level annotation must apply at the point of reference as
follows:
. a property/field within a class in package
(e.g _exmple.po)_ whose reference type is _@XmlSchemaType.type()_ . For
e.g.
// XMLGregorianCalendar will be mapped to XML
Schema type "date"
XMLGregorianCalendar cal;
. a property/field within a class in package
(e.g _exmple.po)_ , where _@XmlSchemaType.type()_ is used as a
parametric type. For e.g.
// Example: Following code maps to a
repeating element with
// XML Schema type of "date".
List<XMLGregorianCalendar> bar;
property/field:
A _@XmlSchemaType_ specified on the
property/field maps references to _@XmlSchemaType.type()_ as follows:
. property/field is a single valued.
// Maps XMLGregorianCalendar to XML Schema
type "date"”
@XmlSchemaType(name=”date”)
public XMLGregorianCalendar cal;
. a property/field where
_@XmlSchemaType.type()_ is used as a parametric type. For e.g.
// Example: Following code maps to a
repeating element with
// XML Schema type of "date".
@XmlSchemaType(name="date")
List<XMLGregorianCalendar> bar;
=== @XmlSchemaTypes
This annotation is a container annotation for
defining multiple _@XmlSchemaType_ annotations at the package level.
=== Synopsis
@Retention(RUNTIME) @Target(\{PACKAGE})
public @interface XmlSchemaTypes \{
// Collection of @\{@link XmlSchemaType}
annotations
XmlSchemaType[] value();
}
=== Mapping
Each _@XmlSchemaType_ annotation in
_@XmlSchemaTypes.value()_ must be mapped as specified in
link:jaxb.html#a2520[See @XmlSchemaType]”.
=== Java class
=== [[a2578]]@XmlType
_@XmlType_ is used to map a Java class to a
schema type. The schema type is computed from its annotation element
values.
=== Synopsis
@Retention(RUNTIME) @Target(\{TYPE})
public @interface XmlType \{
String name() default "##default";
String[] propOrder() default \{""};
String namespace() default "##default" ;
Class factoryClass() default DEFAULT.class;
static final class DEFAULT \{};
String factoryMethod() default "";
}
=== [[a2591]]Mapping
The following mapping constraints must be
enforced:
* a class must be either be a top level class
or a nested static class.
* a class must have a public or protected
no-arg constructor or a factory method identified by \{ _factoryClass(),
factoryMethod()_ } unless it is adapted using _@XmlJavaTypeAdapter_ .
* If _factoryClass()_ is other than
DEFAULT.class, then _factoryMethod()_ must be specified (i.e. the
default value ““ cannot be used.)
* If _factoryClass()_ is _DEFAULT.class_ and
_factoryMethod()_ is not ““, then _factoryMethod()_ be a method in this
class.
* if _@XmlType.propOrder_ is not \{} or \{““},
then the set must include all of the properties and fields mapped to
particles as specified in:
* link:jaxb.html#a2898[See
@XmlElement]”
* link:jaxb.html#a3019[See
@XmlElements]”
* link:jaxb.html#a3049[See
@XmlElementRef]”
* link:jaxb.html#a3112[See
@XmlElementRefs]”
* _@XmlType.propOrder_ must not include a
field or property annotated with _@XmlTransient._
* if the class, subClass, derives from another
XML-bound class, baseClass directly or indirectly (other than
java.lang.Object), then the subClass must not contain a mapped property
or field annotated with _@XmlValue_ annotation.
* If a class contains a mapped property or
field annotated with _@XmlValue_ annotation, then all other mapped
fields or properties in the class must be mapped to an XML attribute.
* This annotation can be used with the
following annotations: _@XmlRootElement, @XmlAccessorOrder,
@XmlAccessorType._
* Even though the syntax allows it, @XmlType
is disallowed on an interface.
A class annotated with @ _XmlType_ , must be
mapped as specified below:
class must be mapped as specified in
link:jaxb.html#a2678[See Mapping: Class to Simple Type
Definition] if the class contains only one mapped property or field that
is annotated with @ _XmlValue_ as specified in
link:jaxb.html#a3331[See @XmlValue]”.
otherwise, the class must be mapped as
specified in link:jaxb.html#a2611[See Mapping: Class to Complex
Type
Definition].
=== [[a2611]]Mapping: Class to Complex Type Definition
\{name}
if _@XmlType.name()_ is ““, then absent
otherwise if _@XmlType.name()_ is “
_##default_ “, then the XML name derived from the class name as
specified in link:jaxb.html#a3678[See Java Identifier To XML
Name]”
otherwise _@XmlType.name()_
\{target namespace}
{empty}if _@XmlType.namespace()_ is “
_##default_ “ && _@XmlType.name()_ is ““ and class is annotated with
_@XmlRootElement_ , then the \{target namespace} as specified in
link:jaxb.html#a2742[See Mapping: Class to Element Declaration]
otherwise if _@XmlType.namespace()_ is “
_##default_ “ && _@XmlType.name()_ is ““ and class is not annotated with
_@XmlRootElement_ , then the \{target namespace} of the attribute or
element to which the property or field, from where this class is
referenced, is mapped.
{empty}otherwise if _@XmlType.namespace()_ is
“ _##default_ “ && _@XmlType.name()_ is not ““, then the namespace to
which the package, in which class is defined, is mapped as specified in
link:jaxb.html#a2476[See Mapping: Package to XML target
namespace]
otherwise _@XmlType.namespace()_
\{base type definition}
if the class contains a mapped property or
field annotated with _@XmlValue_ as specified in
link:jaxb.html#a3331[See @XmlValue]”, then the schema type to
which mapped property or field’s type is mapped.
otherwise schema type to which the nearest
XML-bound ancestor class is mapped
*
*
\{derivation method}
if _\{base type definition}_ is _xs:anyType_ ,
then by _restriction_
otherwise _extension_
\{final}
if class modifier final is present. then the
set \{extension, restriction};
otherwise, the empty set.
\{abstract}
true if the class modifier abstract is
present;
otherwise false.
\{attribute uses}
The set of properties or fields mapped to
attributes as specified in link:jaxb.html#a3230[See
@XmlAttribute]”.
\{attribute wildcard}
Attribute wildcard as specified in
link:jaxb.html#a3303[See XmlAnyAttribute]”.
\{content type}
. empty if no mapped property or field is
annotated with _@XmlElement_
. _mixed_ if a property or field is annotated
with _@XmlMixed_ as specified in link:jaxb.html#a3449[See
@XmlMixed]”.
. _simpleContent_ if :
. no property or field is annotated with
_@XmlElement_
. && one or more properties or fields is
annotated with _@XmlAttribute_
. && one property is annotated with
_@XmlValue_ .
. _element-only content_ if one or more
properties is annotated with _@XmlElement; +
content model_ mapped as specified in link:jaxb.html#a2662[See
Mapping: Class body to Model Group Component]”.
\{prohibited substitutions}
Empty set
*
\{annotations}
_absent_
=== [[a2662]]Mapping: Class body to Model Group Component
\{compositor}
if _@XmlType.propOrder()_ is \{} then _xs:all_
;
otherwise _xs:sequence_ . The ordering of
particles is:
if _@XmlType.propOrder()_ is not ““, then the
order in which properties/fields are listed in _@XmlType.propOrder()_ .
if _@XmlType.propOrder()_ is ““ &&
class is annotated with
_@XmlAccessorOrder(XmlAcessOrder.ALPHABETICAL) )_ or
_@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)_ is specified at the
package level and class is not annotated with
_@XmlAccessorOrder(XmlAccessOrder.UNDEFINED)_ , then alphabetical order
as specified in link:jaxb.html#a2506[See @XmlAccessorOrder]”.
otherwise order is unspecified.
\{particles}
Set of properties or fields mapped to
particles. See _\{compositor}_ mapping above for ordering of particles.
\{annotation}
_unspecified_
=== [[a2678]]Mapping: Class to Simple Type Definition
\{name}
if _@XmlType.name()_ is ““, then absent
otherwise if _@XmlType.name()_ is “
_##default_ “,
then the XML name derived from the class name
as specified in link:jaxb.html#a3678[See Java Identifier To XML
Name]”
otherwise _@XmlType.name()_
\{target namespace}
{empty}if _@XmlType.namespace()_ is “
_##default_ “ && _@XmlType.name()_ is ““ and class is annotated with
_@XmlRootElement_ , then the \{target namespace} as specified in
link:jaxb.html#a2742[See Mapping: Class to Element Declaration]
otherwise if _@XmlType.namespace()_ is “
_##default_ “ && _@XmlType.name()_ is ““ and class is not annotated with
_@XmlRootElement_ , then the \{target namespace} of the attribute or
element to which the property or field, from where this class is
referenced, is mapped.
{empty}otherwise if _@XmlType.namespace()_ is
“ _##default_ “ && _@XmlType.name()_ is not ““, then the namespace to
which the package, in which class is defined, is mapped as specified in
link:jaxb.html#a2476[See Mapping: Package to XML target
namespace]
otherwise _@XmlType.namespace()_
\{base type definition}
ur-type definition, _xs:anyType_ .
NOTE: This is subject to the mapping
constraints on XmlType. See link:jaxb.html#a2591[See Mapping]”.
\{facets}
_empty set_
\{fundamental facets}
derived
\{final}
empty set.
A subset of \{extension, list, restriction,
union}.
\{variety}
Must be mapped as shown below
atomic
_\{primitive type definition}_
if property or field type is one of:
- primitive type
- wrapper class
- reference type mapped to a simple atomic
type.
list
_\{item type definition}_
if the property or field type is one of the
following collection types:
- generic list
- indexed property
- single dimensional array
{empty}link:jaxb.html#a3800[See
@XmlType: List simple type]
union
_\{member type definitions}_
Not mapped.
\{annotation}
_unspecified_
=== @XmlRootElement
_@XmlRooElement_ can be used to associate a
global element with the schema type to which a class is mapped.
=== Synopsis
@Retention(RUNTIME) @Target(\{TYPE}
public @interface XmlRootElement \{
String name() default "##default" ;
String namespace() default "##default" ;
}
=== Mapping
The following mapping constraints must be
enforced:
. The only other annotations allowed with this
annotation are: _@XmlType, @XmlEnum, @XmlAccessorType,
@XmlAcessorOrder._
A class annotated with _@XmlRootElement_
annotation, must be mapped as specified in
link:jaxb.html#a2742[See Mapping: Class to Element Declaration].
=== Mapping: Class [[a2742]]to Element Declaration
\{name}
if _@XmlRootElement.name()_ is “##default“,
then the XML name derived from the class name as specified in
link:jaxb.html#a3678[See Java Identifier To XML Name]”;
otherwise _@XmlRootElement.name()_
\{target namespace}
{empty}if _@XmlRootElement.namespace()_ is “
_##default_ “ _,_ then the value of the targetNamespace to which the
package containing the class is mapped as specified in
link:jaxb.html#a2476[See Mapping: Package to XML target
namespace]
otherwise _@XmlRootElement.namespace()_
\{type definition}
schema type to which the class is mapped as
specified in link:jaxb.html#a2578[See @XmlType]”.
\{scope}
_global_
\{value constraint}
_absent_
\{nillable}
_false_
\{identity-constraint definitions}
empty set
\{substitution group affiliation}
_absent_
*
\{substitution group exclusions}
_\{extension, restriction}_
\{disallowed substitution}
_\{substitution,extension,restriction}_
\{abstract}
_false_
*
\{annotation}
_unspecified_
=== @XmlTransient
_@XmlTransient_ is used to prevent the
mapping of a class.
=== Synopsis
@Retention(RUNTIME) @Target(TYPE)
public @interface XmlTransient \{}
=== Mapping
The class must not be mapped. Any reference to
this class from the other XML-bound classes will treated as if they are
refering to the nearest XML-bound ancestor of this class (which could be
_java.lang.Object_ , which guarantees that there always exists such a
class.)
For the effect that this annotation causes on
derived classes, see link:jaxb.html#a2611[See Mapping: Class to
Complex Type Definition].
Note that a class with _@XmlTransient_ may
still have properties and fields with JAXB annotations. Those are mapped
to XML when a derived class is mapped to XML. See section
link:jaxb.html#a2876[See Property And Field] for more details.
The following mapping constraints must be
enforced:
* _@XmlTransient_ is mutually exclusive with
all other mapping annotations.
=== @XmlSeeAlso
_@XmlSeeAlso_ is an annotation that can be
optionally placed on a class to instruct the JAXB runtime and the schema
generator to also bind classes listed in _@XmlSeeAlso_ , when it binds
the class that _@XmlSeeAlso_ is on.
=== Synopsis
@Retention(RUNTIME) @Target(TYPE)
public @interface XmlRootElement \{
Class[] value();
}
=== Enum Type
=== @XmlEnum
=== Synopsis
@Retention(RUNTIME) @Target(\{TYPE}
public @interface XmlEnum \{
// Java type that is mapped to a XML simple
type
Class <?> value() default String.class;
}
=== Mapping
The following mapping constraints must be
enforced:
_@XmlEnum.value()_ must be mapped to a XML
schema simple type.
=== Mapping: Enum type to Base Type Definition
\{base type definition}
schema type to which _@XmlEnum.value()_ is
mapped.
\{variety}
The value depends upon the schema type to
which the _@XmlEnum.value()_ is mapped. But syntactically, it is always
a restriction of \{base type definition}.
derived from the \{base type definition}
*
=== @XmlEnumValue
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD}
public @interface XmlEnumValue \{
String value();
}
=== Mapping
The following mapping constraints must be
enforced:
* _@XmlEnumValue.value()_ must have a valid
lexical representation for _@XmlEnum.value()_ .
=== Mapping: Enum constant to Enumeration Schema Component
\{value}
_@XmlEnumValue.value()_
\{annotation}
unspecified
=== @XmlType
=== Synopsis
@Retention(RUNTIME) @Target(\{TYPE})
public @interface XmlType \{
String name() default "##default";
String namespace() default "##default" ;
String[] propOrder() default \{""};
Class factoryClass() default DEFAULT.class;
static final class DEFAULT \{};
String factoryMethod() default ““;
}
=== [[a2837]]Mapping
The following mapping constraints must be
enforced:
. _factoryMethod(),factoryClass()_ and
_@XmlType.propOrder_ must be ignored.
. This annotation can be used only with the
following other annotations: _@XmlRootElement, @XmlAccessorOrder,
@XmlAccessorType._ However, _@XmlAccessorOrder_ and _@XmlAccessorType_
must be ignored; they are not meaningful when used to annotate an enum
type.
=== @XmlRootElement
_@XmlRootElement_ can be used to associate a
global element with the schema type to which the enum type is mapped.
The following mapping constraints must be
enforced:
. The only other annotations allowed with this
annotation are: _@XmlType, @XmlEnum, @XmlAccessorType,
@XmlAcessorOrder._ Note that _@XmlAccessorType_ and _@XmlAccessorOrder_
while allowed will be ignored by the constraint in
link:jaxb.html#a2837[See Mapping].
The mapping must be performed as specified in
link:jaxb.html#a2846[See Mapping: Enum type to Element
Declaration].
=== [[a2846]]Mapping: Enum type to Element Declaration
\{name}
if _@XmlRootElement.name()_ is “##default“,
then the XML name derived from the enum type name as specified in
link:jaxb.html#a3678[See Java Identifier To XML Name]”;
otherwise _@XmlRootElement.name()_
\{target namespace}
{empty}if _@XmlRootElement.namespace()_ is “
_##default_ “ _,_ then the value of the targetNamespace to which the
package containing the class is mapped as specified in
link:jaxb.html#a2476[See Mapping: Package to XML target
namespace]
otherwise _@XmlRootElement.namespace()_
\{type definition}
schema type to which the class is mapped as
specified in link:jaxb.html#a2578[See @XmlType]”.
\{scope}
_global_
\{value constraint}
_absent_
\{nillable}
_false_
\{identity-constraint definitions}
empty set
\{substitution group affiliation}
_absent_
*
\{substitution group exclusions}
_\{extension, restriction}_
\{disallowed substitution}
_\{substitution,extension,restriction}_
\{abstract}
_false_
\{annotation}
_unspecified_
=== [[a2876]]Property And Field
The following must be mapped (subject to the
mapping constraints listed below):
* read/write property as identified by
java.beans.Introspector.getBeanInfo with its nearest XML-bound
superclass as the stopClass.
* non static, non transient field of all the
ancestors up to the stopClass (but excluding the stopClass itself); if
annotated with _@XmlAttribute_ , then static final field must be mapped
(informally this maps to a fixed attribute but this is formally
specified in the mapping tables below).
A mapped property is a property found as above
and mapped either by default or using a JAXB annotation.
A mapped field is a field found as above and
mapped either by default or using a JAXB annotation.
A property or field that has been annotated
with _@XmlTransient_ is not mapped.
The following mapping constraints must be
enforced.
* For a property, a given annotation can be
applied to either read or write property but not both.
* A property name must be different from any
other property name in any of the super classes of the class being
mapped. +
* A mapped field name or the de capitalized
name of a mapped property must be unique within a class. For e.g.
// Example 1:
// Both the field “x” and property getX/setX
are mapped by
// default. However, the decapitalized name
property getX/setX
// is also “x” which collides with the field
name “x”.
public class Foo \{
public int x;
public int getX \{..};
public void setX \{..};
}
=== [[a2898]]@XmlElement
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD}
public @interface XmlElement \{
String name() default "##default" ; // name
for XML element
boolean nillable() default false;
boolean required() default false;
String namespace() default "##default" ;
Class type() default DEFAULT.class;
String defaultValue() default "\u0000";
static final class DEFAULT \{}
}
=== Mapping
The following mapping constraints must be
enforced:
* The only additional mapping annotations
allowed with _@XmlElement_ are: _@XmlID, @XmlIDREF, @XmlList,
@XmlSchemaType, @XmlValue, @XmlAttachmentRef, @XmlMimeType,
@XmlInlineBinaryData, @XmlJavaTypeAdapter_ and _@XmElementWrapper.
@XmlElement_ can also be used within _@XmlElements_ .
* If the property or field type is a
parametric collection type, then _@XmlElement.type()_ must be
_DEFAULT.class_ or _collectionitem.class_ (since the type of the
collection is already known).
A field or property annotated must be mapped
as follows:
* If _@XmlElement.namespace()_ is not “
_##default_ ” and different from the _\{target namespace}_ of the
enclosing class, then it must be mapped as specified in
link:jaxb.html#a2941[See Mapping: Property/field to Particle -
ref attribute].
* If property is single valued, and it’s type
is annotated with _@XmlRootElement_ and _@XmlType.name()= ““_ , then the
property must be mapped as specified in link:jaxb.html#a2941[See
Mapping: Property/field to Particle - ref attribute].
Design Note: This mapping is designed to
eliminate an infinite recursion. For example:
// Code fragment
@XmlRootElement
@XmlType(name="")
class Foo \{
Foo foo;
}
In the absence of the above mapping, the above
code would map to:
<schema>
<element name="foo">
<complexType>
<sequence>
<element name=”foo” minOccurs=”0”>
<complexType>
... infinite recursion ...
With the above mapping, the code fragment
would instead map to:
<schema>
<element name="foo">
<complexType>
<sequence>
<element ref=”foo” minOccurs=”0”>
* otherwise, it must be mapped as
link:jaxb.html#a2959[See Mapping: Property/field to Particle -
no ref attribute].
*
=== Mapping: Property/field to [[a2941]]Particle - ref attribute
\{min occurs}
if _@XmlElement.required()_ is true, then 1
if the property type is a primitive type or a
multi dimensional array with a primitive type then 1
otherwise 0
\{max occurs}
if the type of the property/field is not a
collection type, then 1
otherwise _unbounded_ .
\{term}
element declaration as specified in
link:jaxb.html#a2973[See Mapping: Property/field to Element
declaration] with the following overrides for the abstract schema
component properties:
\{scope} is _global_
_\{value constraint}_ is _absent_
_\{type definition}_ is _xs:anyType_ if the
mapping results in two or more element decalarations with the same name.
Note: The above make the element a global
element declaration rather than a local element declaration.
=== [[a2959]]Mapping: Property/field to Particle - no ref attribute
\{min occurs}
if _@XmlElement.required()_ is true, then 1
otherwise if the property type is a primitive
type or a multi dimensional array with a primitive type then 1
otherwise 0
\{max occurs}
if the type of the property/field is not a
collection type, then 1;
otherwise _unbounded_ .
\{term}
must be mapped as specified in
link:jaxb.html#a2973[See Mapping: Property/field to Element
declaration].
=== Mapping: [[a2973]]Property/field to Element declaration
\{name}
if _@XmlElement.name()_ is _“##default”,_ then
the XML name derived from the property or field name as specified in
link:jaxb.html#a3678[See Java Identifier To XML Name]”;
otherwise _@XmlElement.name()_
\{target namespace}
if _@XmlElement.namespace()_ is “ _##default_
“, then
if the enclosing package has @ _XmlSchema_
annotation and is _@XmlSchema.elementFormDefault_ is
_@XmlNsForm.QUALIFIED_ , then the namespace of the enclosing class. +
+
otherwise ““ (which produces unqualified element in the default
namespace).
otherwise, _@XmlElement.namespace()_
\{type definition}
Note: The order of type inference below is
significant.
if _@XmlElement.type()_ is not _DEFAULT.class_
, then the schema type to which _@XmlElement.type()_ is mapped.
otherwise if annotated with _@XmlList,_ schema
type derived by mapping as specified in link:jaxb.html#a3399[See
@XmlList]”
otherwise if annotated with _@XmlValue_ ,
schema type derived by mapping as specified in
link:jaxb.html#a3331[See @XmlValue]”
otherwise if annotated with _@XmlID_ , the
schema type derived by mapping as specified in
link:jaxb.html#a3377[See @XmlID]”
otherwise if annotated with _@XmlIDREF_ , the
schema type derived by mapping as specified in
link:jaxb.html#a3387[See @XmlIDREF]”
otherwise if the property or field is a
collection type, then the schema type derived by mapping the collection
item type.
otherwise the schema type to which the type of
the property is mapped.
\{scope}
complex type to which the property’s or the
field’s containing class is mapped as specified in
link:jaxb.html#a2456[See @XmlSchema]”.
\{value constraint}
if @XmlElement.defaultValue() is "\u0000" then
_absent_
otherwise default value with the value
_@XmlElement.defaultvalue()_ .
\{nillable}
_@XmlElement.nillable()_
\{identity-constraint definitions}
_absent_
\{substitution group affiliation}
_absent_
\{substitution group exclusions}
\{ _extension, restriction_ }
\{disallowed substitution}
\{ _extension, restriction,substitution_ }
\{abstract}
_false_
\{annotation}
_unspecified_
.
=== [[a3019]]@XmlElements
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD,METHOD})
public @interface XmlElements \{
XmlElement[] value(); // collection of
@XmlElement annotations
}
=== Mapping
The following mapping constraints must be
enforced:
* If the property or field type is a
parameterized collection type, then the size of the
_@XmlElements.value()_ must be 1.
* This annotation can be used only with the
following annotations: _@XmlIDREF, @XmlElementWrapper,
@XmlJavaTypeAdapter._
* If _@XmlIDREF_ is specified, then each
_@XmlElement.type()_ must contain a JavaBean property/field annotated
with _@XmlID_ .
The property or field must be mapped as
follows:
* If the size of _@XmlElements.value()_ is 1,
then the property must be mapped as specified in
link:jaxb.html#a2898[See @XmlElement]”.
* otherwise it must be mapped as specified in
link:jaxb.html#a3034[See Mapping: List of types to choice
particle].
=== [[a3034]]Mapping: List of types to choice particle
\{min occurs}
0
\{max occurs}
_unbounded_
\{term}
{empty}If \{particples} row in
link:jaxb.html#a3042[See Mapping: List of types to choice model
group of elements] results in a single particle, then that single
particle. Otherwise mapped as specified in
link:jaxb.html#a3042[See Mapping: List of types to choice model
group of elements]
=== [[a3042]]Mapping: List of types to choice model group of elements
\{compositor}
_choice_
\{particles}
set obtained by mapping each _@XmlElement_ in
_@XmlElements.value()_ as specified in link:jaxb.html#a2973[See
Mapping: Property/field to Element declaration].
\{annotation}
_unspecified_
=== [[a3049]]@XmlElementRef
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD}
public @interface XmlElementRef \{
String name() default "##default" ; // name
for XML element
String namespace() default "##default" ;
Class type() default DEFAULT.class;
static final class DEFAULT \{}
}
=== Mapping
The following mapping constraints must be
enforced:
* The only other additional JAXB mapping
annotations allowed with _@XmlElementRef_ are: _@XmlElementWrapper_ and
_@XmlJavaTypeAdapter._
* If the collection item type or property type
(for single valued property) is _jakarta.xml.bind.JAXBElement_ , then \{
_@XmlElementRef.name()_ , _@XmlElementRef.namespace()}_ must point an
element factory method with an _@XmlElementDecl_ annotation in a class
annotated with _@XmlRegistry_ (usually _ObjectFactory_ class generated
by the schema compiler) :
* _@XmlElementDecl.name()_ must equal
_@XmlElementRef.name()_
* _@XmlElementDecl.namespace()_ must equal
_@XmlElementRef.namespace()_ .
* If the collection item type (for collection
property) or property type (for single valued property) is not
_jakarta.xml.bind.JAXBElement_ , then the type referenced by the property
or field must be annotated with _@XmlRootElement_ .
A field or property annotated with the
_@XmlElementRef_ annotation must be mapped as follows:
* if the type of the property or field is
single valued property, then it must be mapped as specified in
link:jaxb.html#a3078[See Mapping: Property/field (property type
single valued) to Particle with ref attribute]
* otherwise (the type of the property or field
is a parametric type), then it must be mapped as specified in
link:jaxb.html#a3097[See Mapping: Property/Field (parametric
type) to choice particle].
+
=== [[a3078]]Mapping: Property/field (property type single valued) to Particle with ref attribute
\{min occurs}
1
\{max occurs}
1
\{term}
must be mapped as specified in
link:jaxb.html#a3085[See Mapping: Property/field to Element
declaration with ref attribute].
=== [[a3085]]Mapping: Property/field to Element declaration with ref attribute
\{name}
if _@XmlElementRef.type()_ is
_@XmlElementRef.DEFAULT.class_ and the property type is not
_jakarta.xml.bind.JAXBElement_ , then the XML name
_@XmlRootElement.name()_ on the type being referenced.
otherwise if _@XmlElementRef.type()_ is
_@XmlElementRef.DEFAULT.class_ and the parametric type or the property
type (for single valued property) is a _jakarta.xml.bind.JAXBElement_ ,
then the _@XmlElementRef.name()_
\{target namespace}
if _@XmlElementRef.type()_ is
_@XmlElementRef.DEFAULT.class_ and the property type is not
_jakarta.xml.bind.JAXBElement_ , then the XML namespace of the type being
referenced.
__
otherwise if _@XmlElementRef.type()_ is
_@XmlElementRef.DEFAULT.class_ and the property type is single valued
and is _jakarta.xml.bind.JAXBElement_ , then the
_@XmlElementRef.namespace()_
\{annotation}
_unspecified_
=== [[a3097]]Mapping: Property/Field (parametric type) to choice particle
\{min occurs}
_0_
\{max occurs}
_unbounded_
\{term}
{empty}If \{particles} row in
link:jaxb.html#a3105[See Mapping: Property/field (parametric
type) to choice model group of element refs] results in single particle,
then that single particle. Otherwise mapped as specified in
link:jaxb.html#a3105[See Mapping: Property/field (parametric
type) to choice model group of element refs]
=== [[a3105]]Mapping: Property/field (parametric type) to choice model group of element refs
\{compositor}
_choice_
\{particles}
set obtained by visiting parametric type and
each of its derived types and if annotated with @XmlRootElement, then
mapping the @XmlRootElement as specified in as specified in
link:jaxb.html#a3085[See Mapping: Property/field to Element
declaration with ref attribute].
\{annotation}
_unspecified_
=== [[a3112]]@XmlElementRefs
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD,METHOD})
public @interface XmlElementRefs \{
XmlElementRef[] value();
}
=== Mapping
The following mapping constraints must be
enforced:
* The only other additional JAXB mapping
annotations allowed with @XmlElementRefs are: _@XmlElementWrapper_ and @
_XmlJavaTypeAdapter_ .
The property or field must be mapped as
specified in link:jaxb.html#a3124[See Mapping: List of element
instances to choice particle].
=== [[a3124]]Mapping: List of element instances to choice particle
\{min occurs}
_0_
\{max occurs}
_unbounded_
\{term}
{empty}If the \{particles} row in
link:jaxb.html#a3132[See Mapping: List of element instances to
choice model group of element refs] results in a single particle, then
that single particle. Otherwise mapped as specified in
link:jaxb.html#a3132[See Mapping: List of element instances to
choice model group of element refs]
=== [[a3132]]Mapping: List of element instances to choice model group of element refs
\{compositor}
_choice_
\{particles}
set obtained by mapping
* each _@XmlElementRef_ in
_@XmlElementRefs.value()_ as specified in
link:jaxb.html#a3049[See @XmlElementRef]”.
* if property is annotated with
_@XmlAnyElement,_ then the particle obtained by mapping as specified in
link:jaxb.html#a3210[See @XmlAnyElement]”
\{annotation}
_unspecified_
=== @XmlElementWrapper
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD}
public @interface XmlElementWrapper \{
String name() default "##default" ; // name
for XML element
String namespace() default "##default" ;
boolean nillable() default false;
boolean required() default false;
}
=== Mapping
The following mapping constraints must be
enforced:
* The only additional mapping annotations
allowed with _@XmlElementWrapper_ are: _@XmlElement, @XmlElements,
@XmlElementRef, @XmlElementRefs, @XmlJavaTypeAdapter._
* The property or the field must be a
collection property.
The property or field must be mapped as
follows:
* If _@XmlElementWrapper.namespace()_ is not “
_##default_ ” and different from the _\{target namespace}_ of the
enclosing class, then it must be mapped as specified as specified in
link:jaxb.html#a3202[See Mapping: Property/field Element Wrapper
with ref attribute].
* otherwise, it must be mapped as
link:jaxb.html#a3158[See Mapping: Property/field to Particle for
Element Wrapper].
=== [[a3158]]Mapping: Property/field to Particle for Element Wrapper
\{min occurs}
if _@XmlElementWrapper.nillable()_ is true or
_@XmlElementWrapper.required()_ is true, then 1;
otherwise 0
\{max occurs}
1
\{term}
must be mapped as specified in
link:jaxb.html#a3167[See Mapping: Property/field to Element
Declaration for Element Wrapper].
=== Mapping: Property/field to Element Declaration for Element Wrapper [[a3167]]
\{name}
if _@XmlElementWrapper.name()_ is “
_##default_ “, then the XML name derived from the property or field name
as specified in link:jaxb.html#a3678[See Java Identifier To XML
Name]”;
otherwise _@XmlElementWrapper.name()_
\{target namespace}
if _@XmlElementWrapper.namespace()_ is “
_##default_ “,
if the enclosing package has @ _XmlSchema_
annotation and is _@XmlSchema.elementFormDefault_ is
_@XmlNsForm.QUALIFIED_ , then the namespace of the enclosing class. +
+
otherwise ““ (which produces unqualified element in the default
namespace).
otherwise _@XmlElementWrapper.namespace()_
\{type definition}
{empty}if property/field is annotated with
_@XmlElementRef_ or _@XmlElementRefs_ then the schema type as specified
in link:jaxb.html#a3124[See Mapping: List of element instances
to choice particle]
otherwise if property/field is annotated with
_@XmlElement_ or _@XmlElements_ then the schema type as specified
inlink:jaxb.html#a3034[See Mapping: List of types to choice
particle].
\{scope}
complex type to which the property’s or the
field’s containing class is mapped.
\{value constraint}
_absent_
\{nillable}
_@XmlElementWrapper.nillable()_
\{identity-constraint definitions}
_absent_
\{substitution group affiliation}
_absent_
\{substitution group exclusions}
\{ _extension, restriction_ }
\{disallowed substitution}
\{ _extension, restriction,substitution_ }
\{abstract}
_false_
\{annotation}
_unspecified_
=== [[a3202]]Mapping: Property/field Element Wrapper with ref attribute
\{min occurs}
1
\{max occurs}
1
\{term}
element declaration whose \{name} is
_@XmlElementWrapper.name()_ and \{target namespace} is
_@XmlElementWrapper.namespace()._
Note: The element declaration is assumed to
already exist and is not created.
=== [[a3210]]@XmlAnyElement
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD})
public @interface XmlAnyElement \{
boolean lax() default false;
Class<? extends DomHandler> value() default
W3CDomHandler.class;
}
=== Mapping
The following mapping constraints must be
enforced:
* The only other JAXB annotations allowed with
_@XmlAnyElement_ are: _@XmlElementRefs._
* There must be only one property or field
that is annotated with _@XmlAnyElement_ .
* If a baseType has a property annotated with
_@XmlAnyElement_ , then no other sub type in the inheritance hierarchy
rooted at baseType can contain a property annotated with
_@XmlAnyElement_ .
The property or field must be mapped as
specified in link:jaxb.html#a3223[See Mapping: Wildcard schema
component for wildcard (xs:any)]”.
=== [[a3223]]Mapping: Wildcard schema component for wildcard (xs:any)
\{namespace constraint}
_##other_
\{process contents}
_”lax”_ if _lax()_ is _true_ otherwise
_“skip”_
\{annotation}
_unspecified_
=== [[a3230]]@XmlAttribute
_@XmlAttribute_ is used to map a property or
a field to an XML attribute.
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD})
public @interface XmlAttribute \{
String name() default ##default”;
boolean required() default false;
String namespace() default "##default" ;
}
=== Mapping
The following mapping constraints must be
enforced:
* If the type of the field or the property is
a collection type, then the collection item type must be mapped to
schema simple type. Examples:
@XmlAttribute List<Integer> foo; // legal
@XmlAttribute List<Bar> foo; // illegal if
Bar does not map to a
// schema simple type
* If the type of the field or the property is
a non collection type, then the type of the property or field must map
to a simple schema type. Examples:
@XmlAttribute int foo; // legal
@XmlAttribute Foo foo; // illegal if Foo does
not map to a schema
// simple type
* The only additional mapping annotations
allowed with _@XmlAttribute_ are: _@XmlID, @XmlIDREF, @XmlList,
@XmlSchemaType, @XmlValue, @XmlAttachmentRef, @XmlMimeType,
@XmlInlineBinaryData, @XmlJavaTypeAdapter._
*
The property or field must be mapped as
follows:
* If _@XmlAttribute.namespace()_ is not
“##default” and differs from the _\{target namespace}_ of the schema
type to which the type containing the property or field is mapped, then
the property or field must be mapped as specified in
link:jaxb.html#a3255[See Mapping: Property/field to Attribute
Use (with ref attribute)].
* otherwise, it must be mapped as specified in
link:jaxb.html#a3266[See Mapping: Property/field to Attribute
Use (no ref attribute)].
=== [[a3255]]Mapping: Property/field to Attribute Use (with ref attribute)
\{required}
_@XmlAttribute.required()_
\{attribute declaration}
attribute declaration whose \{name} is
_@XmlAttribute.name()_ and \{target namespace} is
_@XmlAttribute.namespace()._
For e.g.
_<xs:attribute ref=”xml:lang”/>_
\{value constraint}
_absent_
\{annotation}
_unspecified_
=== [[a3266]]Mapping: Property/field to Attribute Use (no ref attribute)
\{required}
_@XmlAttribute.required()_
\{attribute declaration}
Mapped as specified in
link:jaxb.html#a3276[See Mapping: Property/field to Attribute
Declaration]”
\{value constraint}
if field has access modifiers public and
static then the _fixed_
otherwise _absent_
=== [[a3276]]Mapping: Property/field to Attribute Declaration
\{name}
if _@XmlAttribute.name()_ is “##default“, then
the XML name derived from the property or field name as specified in
link:jaxb.html#a3678[See Java Identifier To XML Name]”;
otherwise _@XmlAttribute.name()_ .
\{target namespace}
if _@XmlAttribute.namespace()_ is
_“##default”,_ then value of targetNamespace in
link:jaxb.html#a2476[See Mapping: Package to XML target
namespace];
otherwise _@XmlType.namespace()_
\{type definition}
if annotated with _@XmlList,_ schema type
derived by mapping as specified in link:jaxb.html#a3399[See
@XmlList]”
otherwise if annotated with _@XmlID_ , the
schema type derived by mapping as specified in
link:jaxb.html#a3377[See @XmlID]”
otherwise if annotated with _@XmlIDREF_ , the
schema type derived by mapping as specified in
link:jaxb.html#a3387[See @XmlIDREF]”
otherwise if the type of the property is a
collection type, then the schema type derived by mapping the collection
item type.
otherwise the schema type to which the type of
the property is mapped.
\{scope}
complex type of the containing class
\{value constraint}
if field has access modifiers static and final
then _fixed_
otherwise _absent_
\{annotation}
_unspecified_
=== [[a3303]]XmlAnyAttribute
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD})
public @interface XmlAnyAttribute\{}
=== Mapping
The following mapping constraints must be
enforced:
* There must be only one property or field in
a class that is annotated with _@XmlAnyAttribute._
* The type of the property or the field must
be _java.util.Map._
* The only other annotations that can be used
on the property or field with _@XmlAnyAttribute_ are:
_@XmlJavaTypeAdapter._
The property or field must be mapped as
specified in link:jaxb.html#a3313[See Mapping: Wildcard schema
component for Attribute Wildcard].”
=== [[a3313]]Mapping: Wildcard schema component for Attribute Wildcard
\{namespace constraint}
_##other_
\{process contents}
_skip_
\{annotation}
_unspecified_
=== @XmlTransient
_@XmlTransient_ is used to prevent the
mapping of a property or a field.
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD,
TYPE})
public @interface XmlTransient \{}
=== Mapping
The following mapping constraints must be
enforced:
* The field or the property must not be
mapped.
* _@XmlTransient_ is mutually exclusive with
all other mapping annotations.
=== [[a3331]]@XmlValue
=== Synopsis
_@Retention(RUNTIME) @Target(\{FIELD,
METHOD})_
_public @interface XmlValue \{}_
=== XmlValue Type Mapping
The following mapping constraints must be
enforced:
. At most one field or a property in a class
can be annotated with @ _XmlValue_ .
. _@XmlValue_ can be used with the following
annotations:
. _@XmlList_ - however this is redundant
since _@XmlList_ maps a type to a schema simple type that derives by
list just as _@XmlValue_ would.
. _@XmlJavaTypeAdapter_
. If the type of the field or property is a
collection type, then the collection item type must map to a simple
schema type. Examples:
// Examples (not exhaustive): Legal usage of
@XmlValue
@XmlValue List<Integer> foo; // int maps to
xs:int
@XmlValue String[] foo; // String maps to
xs:string
@XmlValue List<Bar> foo; // only if Bar maps
to a simple
// schema type
. If the type of the field or property is not
a collection type, then the type of the property or field must map to a
schema simple type.
. The containing class must not extend another
class (other than java.lang.Obect).
=== Mapping
* If the type of the property or field is a
collection type, then the type must be must be mapped as specified in
link:jaxb.html#a3353[See @XmlValue: Mapping to list simple
type]”.
* Otherwise, the schema type to which the type
of the property or field is mapped.
=== [[a3353]]@XmlValue: Mapping to list simple type
\{name}
_absent_
\{target namespace}
\{target namespace} of the attribute or
element to which the property or field is mapped and from where this
type is referenced.
\{base type definition}
ur-type definition, _xs:anyType_ .
\{facets}
_empty set_
\{fundamental facets}
derived
\{final}
#all
\{variety}
list
\{item type definition}
if the field, property or parameter is a
collection type
* if annotated with _@XmlIDREF_ , then
_xs:IDREF_ as specified in link:jaxb.html#a3387[See @XmlIDREF]”
* otherwise the schema type to which the
collection item type is mapped.
otherwise
* if annotated with _@XmlIDREF_ , then
_xs:IDREF_ as specified in link:jaxb.html#a3387[See @XmlIDREF]”
* otherwise the schema type to which the type
of the property, field or the parameter is mapped.
\{annotation}
_unspecified_
=== [[a3377]]@XmlID
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD})
public @interface XmlID \{}
=== XmlID Type Mapping
The following mapping constraints must be
enforced:
* at most one field or property in a class can
be annotated with _@XmlID_ .
* The type of the field or property must be
_java.lang.String_ .
* The only other program annotations allowed
with _@XmlID_ are: _@XmlAttribute_ and _@XmlElement_ .
The type of the annotated program element must
be mapped to _xs:ID._
=== [[a3387]]@XmlIDREF
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD})
public @interface XmlIDREF \{}
=== XmlIDREF Type Mapping
The following mapping constraints must be
enforced:
* If the type of the field or property is a
collection type, then the collection item type must contain a property
or field annotated with _@XmlID_ .
* If the field or property is not a collection
type, then the type of the property or field must contain a property or
field annotated with _@XmlID_ .
Note: If the collection item type or the type
of the property (for non collection type) is _java.lang.Object,_ then
the instance must contain a property/field annotated with _@XmlID_
attribute.
* The only additional mapping annotations
allowed with _@XmlIDREF_ are: _@XmlElement_ , _@XmlAttribute, @XmlList,_
and _@XmlElements, @XmlJavaTypeAdapter._
If the type of the field or property is a
collection type, then each collection item type must be mapped to
_xs:IDREF_ .
If the type of the field or property is single
valued, then the type of the property or field must be mapped to
_xs:IDREF_ .
=== [[a3399]]@XmlList
This annotation maps a collection type to a
list simple type.
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD,
PARAMETER})
public @interface XmlList \{}
=== XmlIList Type Mapping
The following mapping constraints must be
enforced:
* The type of the field, property or parameter
must be a collection type.
* The collection item type must map to a
simple schema type that does not derive by list. For example:
// Examples: Legal usage of @XmlList
@XmlList List<Integer> foo; // int maps to
xs:int
@XmlList String[] foo; // String maps to
xs:string
@XmlList List<Bar> foo; // only if Bar maps
to a simple type
// Example: Illegal usage of @XmlList
public class Foo \{
// @XmlValue maps List to a XML Schema list
simple type
@XmlValue List<Integer> a;
}
class Bar \{
// Use of @XmlList is illegal since Foo
itself mapped
// to a XML Schema list simple type; XML
Schema list simple
// type can't derive from another XML Schema
list simple type
@XmlList List<Foo> y;
}
* The only additional mapping annotations
allowed with _@XmlList_ are: _@XmlElement, @XmlAttribute, @XmlValue_ and
_@XmlIDREF, @XmlJavaTypeAdapter._
The type of the property or field must be
mapped as specified in link:jaxb.html#a3428[See @XmlList:
Mapping to list simple type].
=== [[a3428]]@XmlList: Mapping to list simple type
\{name}
_absent_
\{target namespace}
\{target namespace} of the attribute or
element to which the property or field is mapped and from where this
type is referenced.
\{base type definition}
ur-type definition, _xs:anyType_ .
\{facets}
_empty set_
\{fundamental facets}
derived
\{final}
#all
\{variety}
list
\{item type definition}
if annotated with _@XmlIDREF_ , then xs:IDREF
as specified in link:jaxb.html#a3387[See @XmlIDREF]”
otherwise the schema type to which the
collection item type is mapped.
\{annotation}
_unspecified_
=== [[a3449]]@XmlMixed
This annotation is used for dealing with mixed
content in XML instances.
=== Synopsis
@Retention(RUNTIME) @Target(\{FIELD, METHOD})
public @interface XmlMixed \{}
=== Mapping
The following mapping constraints must be
enforced:
* The only additional mapping annotations
allowed with _@XmlMixed_ are: _@XmlElementRef, @XmlAnyElement,
@XmlJavaTypeAdapter._
The java.lang.String instances must be
serialized as XML infoset text information items.
=== @XmlMimeType
=== Synopsis
@Retention(RUNTIME)
@Target(\{FIELD,METHOD,PARAMETER})
public @interface XmlMimeType \{
// Textual representation of the MIME type,
such as "image/jpeg"
// "image/*", "text/xml; charset=iso-8859-1"
and so on.
String value();
}
=== Mapping
=== @XmlMimeType: Mapping to Foreign Namespace attribute
\{name}
_“expectedContentTypes”_
\{target namespace}
"http://www.w3.org/2005/05/xmlmime"
attribute value
_@XmlMimeType.value()_
=== @XmlAttachmentRef
=== Synopsis
@Retention(RUNTIME)
@Target(\{FIELD,METHOD,PARAMETER})
public @interface XmlAttachmentRef \{ }
=== Mapping
The type of property or field must map to
_ref:swaRef_ .
=== XmlInlineBinaryData
@Retention(RUNTIME)
@Target(\{FIELD,METHOD,TYPE})
public @interface XmlInlineBinaryData \{
}
=== Mapping
This annotation does not impact the schema
generation. See the javadoc for
_jakarta.xml.bind.annotation.XmlInlineBinaryData_ for more details.
=== ObjectFactory Method
The annotations in this section are intended
primarily for use by schema compiler in annotating element factory
methods in the schema derived ObjectFactory class
(link:jaxb.html#a482[See Java Package]”). They are not expected
to be used when mapping existing classes to schema.
=== @XmlElementDecl
=== Synopsis
@Retention(RUNTIME) @Target(\{METHOD})
public @interface XmlElementDecl \{
Class scope() default GLOBAL.class;
// XML namespace of element
String namespace() default "##default";
String name(); // local name of element
//XML namespace name of a substitution
group's head element.
String substitutionHeadNamespace() default
"##default";
//XML local name of a substitution group's
head element.
String substitutionHeadName() default "";
public final class GLOBAL \{}
}
=== Mapping
The following mapping constraints must be
enforced:
* annotation can only be used on an element
factory method (link:jaxb.html#a482[See Java Package]”). The
annotation creates a mapping between an XML schema element declaration
and a element factory method that returns a _JAXBElement_ instance
representing the element declaration. Typically, the element factory
method is generated (and annotated) from a schema into the
_ObjectFactory_ class in a Java package that represents the binding of
the element declaration's target namespace. Thus, while the annotation
syntax allows _@XmlElementDecl_ to be used on any method, semantically
its use is restricted to annotation of element factory method
* class containing the element factory method
annotated with _@XmlElementDecl_ must be annotated with _@XmlRegistry_ .
* element factory method must take one
parameter assignable to _java.lang.Object_ .
* two or more element factory methods
annotated with _@XmlElementDecl_ must not map to element declarations
with identical _\{name}_ _\{target namespace}_ values.
* if type Foo has an element factory method
and is also annotated with @XmlRootElement, then they must not map to
element declarations with identical _\{name}_ and _\{target namespace}_
values.
One example of where the above scenario occurs
is when a developer attempts to add behavior/data to code generated from
schema. For e.g. schema compiler generates an element instance factory
method (e.g. _createFoo_ ) annotated with _@XmlElementDecl_ . But the
developer annotates _Foo_ with _@XmlRootElement_ .
An element factory method must be mapped as
specified in link:jaxb.html#a3518[See Mapping: Element Factory
method to Element Declaration].
=== [[a3518]]Mapping: Element Factory method to Element Declaration
\{name}
_@XmlElementDecl.name()_
\{target namespace}
{empty}if _@XmlElementDecl.namespace()_ is “
_##default_ “ _,_ then the value of the targetNamespace to which the
package of the class containing the factory method is mapped as
specified in link:jaxb.html#a2476[See Mapping: Package to XML
target namespace]
otherwise _@XmlElementDecl.namespace()_
\{type definition}
schema type to which the class is mapped as
specified in link:jaxb.html#a2578[See @XmlType]”.
\{scope}
_global_ if _@XmlElementDecl.scope()_ is
_@XmlElementDecl.GLOBAL_
otherwise the complex type definition to which
the class containing the object factory method is mapped.
\{value constraint}
_absent_
\{nillable}
_false_
\{identity-constraint definitions}
empty set
\{substitution group affiliation}
element declaration derived from
_@XmlElementDecl.name()_ and _@XmlElementDecl.substitutionHeadName()_
\{substitution group exclusions}
_\{}_
\{disallowed substitution}
\{}
\{abstract}
_false_
\{annotation}
_unspecified_
=== Adapter
=== XmlAdapter
public abstract class
XmlAdapter<ValueType,BoundType> \{
// Do-nothing constructor for the derived
classes.
protected XmlAdapter() \{}
// Convert a value type to a bound type.
public abstract BoundType unmarshal(ValueType
v);
// Convert a bound type to a value type.
public abstract ValueType marshal(BoundType
v);
}
For an overview, see the section,
link:jaxb.html#a2278[See Adapter]”.
For detailed information, see the javadocs for
_jakarta.xml.bind.annotation.adapters.XmlAdapter_ and
_jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter._
=== [[a3561]]@XmlJavaTypeAdapter
=== Synopsis
@Retention(RUNTIME)
@Target(\{PACKAGE,FIELD,METHOD,TYPE,PARAMETER})
public @interface XmlJavaTypeAdapter \{
Class<? extends XmlAdapter> value();
Class type() default DEFAULT.class;
static final class DEFAULT \{}
}
For an overview, see
link:jaxb.html#a2278[See Adapter]”.
=== Scope
The scope of _@XmlJavaTypeAdapter_ must cover
the program elements as specified below:
package:
For clarity, the following code example is
used along with normative text.
// Adapts Foo type to MyFoo type
FooAdapter extends XmlAdapter<MyFoo, Foo>
// FooAdapter is installed at the package
level - example.po
@XmlJavaTypeAdapter(value=FooAdapter.class,
type=Foo.class)
A _@XmlJavaTypeAdapter_ that extends
_XmlAdapter <valueType, boundType>_ and is specified as a package level
annotation must adapt _boundType_ at the point of reference as follows:
. a property/field/parameter within a class in
package (e.g _exmple.po)_ whose reference type is _boundType_ . For e.g.
// Foo will be adapted to MyFoo
Foo foo;
. a property/field/parameter within a class in
package (e.g _exmple.po)_ , where _boundType_ is used as a parametric
type. For e.g.
// List<Foo> will be adapted to List<MyFoo>
Foo foo;
class, interface, enum type:
For clarity, the following code example is
used along with normative text.
// Adapts Foo type to MyFoo type
FooAdapter extends XmlAdapter<MyFoo, Foo>
// FooAdapter is specified on class, interface
or enum type. @XmlJavaTypeAdapter(FooAdapter.class)
public class Foo \{...}
A _@XmlJavaTypeAdapter_ that extends
_XmlAdapter <valueType, boundType>_ and is specified on the class,
interface or Enum type (i.e. on a program element that matches meta
annotation @Target=\{type}) must adapt _boundType_ at the point of
reference as follows:
. a property/field whose reference type is
_boundType_ . For e.g.
// Foo will be adapted to MyFoo
Foo foo;
. a property/field where _boundType_ is used
as a parametric type. For e.g.
// List<Foo> will be adapted to List<MyFoo>
List<Foo> foo;
Note: A _@XmlJavaTypeAdapter_ on a class does
not apply to references to it’s sub class.
//Example:
@XmlJavaTypeAdapter(..) public class Foo \{..}
...
public class DerivedFoo extends Foo \{..}
...
public class Bar \{
// XmlJavaTypeAdapter applies to foo;
public Foo foo;
...
// XmlJavaTypeAdaper DOES NOT apply to
derivedFoo;
public DerivedFoo derivedFoo;
}
property/field/parameter:
A _@XmlJavaTypeAdapter_ that extends
_XmlAdapter <valueType, boundType>_ and is specified on the
property/field or parameter must adapt _boundType_ as follows:
. property/field is a single valued and its
type is _boundType_ :
// Foo will be adapted to MyFoo
@XmlJavaTypeAdapter(FooAdapter.class) Foo
foo;
. a property/field where _boundType_ is used
as a parametric type. For e.g.
// List<Foo> will be adapted to List<MyFoo>
List<Foo> foo;
=== Relationship to other annotations
_@XmlJavaTypeAdapter_ must be applied first
before any other mapping annotation is processed. Further annotation
processing is subject to their respective mapping constraints. For
example,
// PtoQAdapter is applied first and therefore
converts type Q to P
// Next foo is mapped with a type of P (not Q)
subject to the
// mapping constraints specified in
@XmlElements.
@XmlJavaTypeAdapter(PtoQAdapter)
@XmlElements(\{
@XmlElement(name="x",type=PX.class),
@XmlElement(name="y",type=PY.class)
})
Q foo;
@XmlType abstract class P \{}
@XmlType class PX extends P \{}
@XmlType class PY extends P \{}
=== Class Inheritance Semantics
When annotated on a class, the use of
_@XmlJavaTypeAdapter_ annotation is subject to the class inheritance
semantics described here. The semantics is described in terms of two
classes: a _BaseClass_ and a _SubClass_ that derives from _BaseClass_ .
There are two cases to consider:
* _@XmlJavaTypeAdapter_ annotates the
_BaseClass_
* _@XmlJavaTypeAdapter_ annotates the
_SubClass_ , a class that derives from _BaseClass_ .
BaseClass: In this case, _@XmlJavaTypeAdapter_
annotates the _BaseClass_ . In this case, the marshalling and
unmarshalling of an instance of property or a field with a static type
of baseClass must follow the schema to which
_XmlJavaTypeAdapter.value()_ is mapped.
//Example: code fragment
@XmlJavaTypeAdapter(..) BaseClass \{..}
public SubClass extends BaseClass \{..}
public BaseClass foo;
public SubClass subFoo = new SubClass();
foo = subFoo;
In the absence of _@XmlJavaTypeAdapter_
annotation, the instance of subFoo is marshalled with an xsi:type:
<foo xsi:type="subClass"/>
With the _@XmlJavaTypeAdapter_ annotation,
however, the instance of subFoo must be marshalled/unmarshalled
following the XML schema for _@XmlJavaTypeAdapter.value()_ .
Subclass: In this case, _@XmlJavaTypeAdapter_
annotates the _SubClass_ . By definition, the annotation does not cover
references to BaseClass. Thus, the schema types to which _SubClass_ and
_BaseClass_ map are not in the same schema type hierarchy. Hence an
object with a static type of _BaseClass_ but containing an instance of
_SubClass_ can’t be marshalled or unmarshalled. An attempt to do so must
fail. For e.g,
// Example: Code fragment
BaseClass\{..}
...
@XmlJavaTypeAdapter(..) SubClass extends
BaseClass \{..}
public class Bar \{
public BaseClass foo;
public SubClass subFoo = new SubClass();
// marshal, unmarshal of foo will fail
foo = subFoo;
// marshal, unmarshal of subFoo will succeed
}
=== @XmlJavaTypeAdapters
This annotation is a container annotation for
defining multiple _@XmlJavTypeAdapters_ annotations at the package
level.
=== Synopsis
@Retention(RUNTIME) @Target(\{PACKAGE})
public @interface XmlJavaTypeAdapters \{
// Collection of @\{@link XmlJavaTypeAdapter}
annotations
XmlJavaTypeAdapter[] value();
}
=== Mapping
Each _@XmlJavaTypeAdapter_ annotation in
_@XmlJavaTypeAdapters.value()_ must be mapped as specified in
link:jaxb.html#a3561[See @XmlJavaTypeAdapter]”.
=== [[a3676]]Default Mapping
This section describes the default mapping of
program elements. The default mapping is specified in terms of default
annotations that are considered to apply to a program element even in
their absence.
=== [[a3678]]Java Identifier To XML Name
The following is the default mapping for
different identifiers:
* class name: a class name is mapped to an XML
name by de capitalization using
_java.beans.Introspector.decapitalize(class name )._
* enumtype name: enumtype name is mapped to an
XML name by de capitalization using
_java.beans.Introspector.decapitalize(enumtype name)._
* A property name (e.g. address) is derived
from JavaBean access method (e.g. getAddress) by JavaBean de
capitalization of the JavaBean property name
_java.beans.Introspector.decapitalize(JavaBeanAccessMethod)_
=== Package
A package must be mapped with the following
default package level mapping annotations:
* _@XmlAccessorType( +
jakarta.xml.bind.annotation.XmlAccessType.PUBLIC_MEMBER)_
* _@XmlAccessorOrder( +
jakarta.xml.bind.annotation.XmlAccessOrder.UNDEFINED)_
*
* _@XmlSchema_
=== Class
Unless _@XmlTransient_ annotation is present,
a class with a public or protected no-arg constructor must be mapped
with the following default mapping annotations: _@XmlType_ .
=== enum type
An enum type must be mapped with the following
default mapping annotations:
* enum type declaration:
@XmlType
@XmlEnum
enum type \{...}
* each enum constant:
@XmlEnumValue (enumConstatEnum.name())
=== Property / Field
If the value of _@XmlAccessorType.value()_ is
_jakarta.xml.bind.annotation.XmlAccessType.NONE_ , then
* properties and fields, unless explicitly
annotated, must be considered to be annotated with _@XmlTransient_ .
If the value of _@XmlAccessorType.value()_ is
_jakarta.xml.bind.annotation.XmlAccessType.PROPERTY_ , then
* properties not explicitly annotated must be
mapped; fields, unless explicitly annotated, must be considered to be
annotated with _@XmlTransient._
If the value of _@XmlAccessorType.value()_ is
_jakarta.xml.bind.annotation.XmlAccessType.FIELD_ , then
* fields not explicitly annotated must be
mapped; properties, unless explicitly annotated, must be considered to
be annotated with _@XmlTransient._
If the value of _@XmlAccessorType.value()_ is
_jakarta.xml.bind.annotation.XmlAccessType.PUBLIC_MEMBER,_ then
* all properties and public fields, unless
annotated with _@XmlTransient_ , must be mapped.
See javadoc for
_@jakarta.xml.bind.annotation.XmlAccessorType_ for further information on
inheritance rules for this annotation.
=== Default Mapping
A property name (e.g. address) must be derived
from JavaBean access method (e.g. getAddress) by JavaBean
decapitalization of the JavaBean property name
_java.beans.Introspector.decapitalize(JavaBeanAccessMethod)_
A single valued property or field must be
mapped with the following default mapping annotation:
_@XmlElement_
*
A property or field with a collection type
must be mapped by with the following default mapping annotation:
* if the property or field is annotated with
_@XmlList_ , then the default mapping annotation is:
@XmlElement
* otherwise the default mapping annotation is:
@XmlElements( \{ @XmlElement(nillable=true)})
=== Map
By default, _java.util.Map<K,V>_ must be
mapped to the following anonymous schema type. The parameterized types K
and V must be mapped as specified in link:jaxb.html#a2386[See
Type Arguments and Wildcards]”. The anonymous schema type is at the
point of reference.
<!-- Default XML Schema mapping for Map<K,V>
-->
<xs:complexType>
<xs:sequence>
<xs:element name="entry"
minOccurs ="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="key" type="xs:anyType"
minOccurs="0"/>
<xs:element name="value" type="xs:anyType"
minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<!-- Default XML Schema mapping for
Map<String, Integer>-->
<xs:complexType>
<xs:sequence>
<xs:element name="entry"
minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="key" type="xs:string"
minOccurs="0"/>
<xs:element name="value" type="xs:int"
minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
The mapping of Map can be customized using
_@XmlJavaTypeAdapter_ annotation.
=== Multidimensional Array
By default, a multidimensional array must be
mapped to a complex type as follows. Note the table specifies a two
dimensional array mapping. If an array is more than two dimensions, then
the mapping is used recursively.
=== Mapping: Two dimensional array to Complex Type Definition
\{name}
If the basetype is a primitive type (e.g.
int[][]) or its corresponding wrapper class (e.g. Integer[][]), then the
name is basetype concatenated with “Array” (e.g. intArray).
otherwise if the basetype is a reference type
(e.g. Foo[][]), then the XML name to which the reference type is mapped
(e.g. foo) concatenated with “Array” (e.g. fooArray).
\{target namespace}
if the basetype is a primitive or its
corresponding wrapper class then "http://jaxb.dev.java.net/array"
__
otherwise the namespace to which the reference
type is mapped (e.g. for Foo[][], the namespace of the XML type to which
Foo is mapped).
\{base type definition}
_xs:anyType_
\{derivation method}
_restriction_
\{final}
_#all_
\{abstract}
false
\{attribute uses}
empty set
\{attribute wildcard}
absent
\{content type}
_element-only content +
content model_ mapped as specified in link:jaxb.html#a3787[See
Mapping: Two dimensional array to sequence model group]”.
\{prohibited substitutions}
Empty set
\{annotations}
_absent_
=== [[a3787]]Mapping: Two dimensional array to sequence model group
\{compositor}
_xs:sequence_
\{particles}
A repeating element defined as follows:
_<xs:element name="item" type=schematype
minOccurs="0" maxOccurs="unbounded" nillable="true"/>_
where schematype is the schema to which the
array’s component type is mapped (e.g. int[][], then “xs:int”; Foo[][]
then “foo” assuming Foo is mapped to the schema type foo.
\{annotation}
_unspecified_
=== Notes
This section contains a collection of notes
intended to aid in the review of this version of the specification. They
are collected here in a separate section and referenced from possibly
multiple places elsewhere in the specification to make the specification
more compact.
=== [[a3800]]@XmlType: List simple type
It is possible to map a homogenous collection
to a simple type with a variety of \{list}. For e.g.
// Code fragment
public class USStateList \{
@XmlValue
List <int> items;
}
// schema fragment
<xs:simpleType name=”USStateList”>
<xs:list itemType=”int”/>
<xs:simpleType>
Other types which can be mapped to a list
simple type include: indexed property, single dimensional arrays.
== CHAPTER 9 -
[[a3815]]Compatibility
This section describes conformance
requirements for an implementor of this specification. A JAXB
implementation must implement these constraints, without exception, to
provide a predictable environment for application development and
deployment.
This section explicitly lists the high level
requirements of this specification. Additional requirements can be found
in other sections of this specification and the associated javadoc for
package _jakarta.xml.bind_ and its subpackages. If any requirements listed
here conflict with requirements listed elsewhere in the specification,
the requirements here take precedence and replace the conflicting
requirements.
A JAXB implementation must implement the
processing model specified in Appendix B,
link:jaxb.html#a3856[See Runtime Processing]”.
A JAXB implementation included in a product
that supports software development must support a schema generator. A
schema generator must support all the Java Types to XML Schema mapping
specified in Section 8, link:jaxb.html#a2236[See Java Types To
XML]”.
A JAXB implementation included in a product
that supports software development must support a schema compiler. All
operating modes of a schema compiler must support all the XML
Schema-to-Java bindings described in this specification. Additionally,
any operating mode must not implement a default binding for XML
Schema-to-Java bindings as an alternative to those specified in Section
6, link:jaxb.html#a694[See Binding XML Schema to Java
Representations]” nor alternative interpretations for the standard
customizations described in Section 7, link:jaxb.html#a1498[See
Customizing XML Schema to Java Representation Binding].”
The default operating mode for a schema
compiler MUST report an error when extension binding declaration is
encountered. All operating modes for a schema compiler MUST report an
error if an invalid binding customization is detected as defined in
Section 7. An extension binding declaration must be introduced in the
following cases:
. to alter a binding customization that is
allowed to be associated with a schema element as specified in Section
7, link:jaxb.html#a1498[See Customizing XML Schema to Java
Representation Binding].”
. to associate a binding customization with a
schema element where it is disallowed as specified in Section 7,
link:jaxb.html#a1498[See Customizing XML Schema to Java
Representation Binding].”
The default operating mode for a schema
compiler MUST report an error when processing a schema that does not
comply with the 2001 W3C Recommendation for XML Schema, [XSD Part 1] and
[XSD Part 2].
A schema compiler MAY support non-default
operating modes for binding schema languages other than XML Schema.
A schema compiler MUST be able to generate
Java classes that are able to run on at least one Sun's Reference
Implementation of the J2SE Java Runtime Environment that is Java SE 5 or
higher.
A schema generator MAY support non-default
operating modes for mapping Java types to schema languages other than
XML Schema.
A Java platform configured with any JAXB 2.0
implementation MUST allow any JAXB 1.0 application, packaged as
specified by the JAXB 1.0 implementation used by the application, to run
as specified by the JAXB 1.0 specification. A JAXB 1.0 application uses
schema-derived classes generated by a JAXB 1.0 compliant schema compiler
and is distributed with the compatible JAXB 1.0 runtime implementation.
Unlike JAXB 2.0, JAXB 1.0 specified a tight coupling between a JAXB 1.0
implementation’s schema-derived code and the JAXB 1.0 implementation of
package _jakarta.xml.bind_ . The required processing model for a JAXB 1.0
schema compiler generated package is specified in
_jakarta.xml.bind.JAXBContext_ class javadoc under the heading _SPEC
REQUIREMENT_ .
== CHAPTER 10 -
References
[XSD Part 0] XML Schema Part 0: Primer, +
Available at _http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/ +
_ (schema fragments borrowed from this widely used source)
[XSD Part 1] XML Schema Part 1: Structures, +
Available at _http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/_
[XSD Part 2] XML Schema Part 2: Datatypes, +
Available at _http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/_
[XMl-Infoset] XML Information Set, John Cowan
and Richard Tobin, eds., W3C, 16 March 2001. Available at
_http://www.w3.org/TR/2001/WD-xml-infoset-20010316/_
[XML 1.0] Extensible Markup Language (XML)
1.0 (Second Edition), +
W3C Recommendation 6 October 2000. +
Available at _http://www.w3.org/TR/2000/REC-xml-20001006_ .
[Namespaces in XML] Namespaces in XML +
W3C Recommendation 14 January 1999. +
Available at _http://www.w3.org/TR/1999/REC-xml-names-19990114_
[XPath], XML Path Language, James Clark and
Steve DeRose, eds., W3C, 16 November 1999. Available at
_http://www.w3.org/TR/1999/REC-xpath-19991116_
[XSLT 1.0] XSL Transformations (XSLT),
Version 1.0, James Clark, W3C Recommendation 16 November 1999. Available
at http://www.w3.org/TR/1999/REC-xslt-19991116.
[BEANS] JavaBeans(TM), Version 1.01, July 24,
1997. Available at _http://java.sun.com/beans_ .
[XSD Primer] XML Schema Part 0: Primer, +
W3C Recommendation 2 May 2001 +
Available at _http://www.w3.org/TR/xmlschema-0/_
[BLOCH] Joshua Bloch, Effective Java, Chapter
3, Typesafe Enums +
_http://developer.java.sun.com/developer/Books/shiftintojavapage1.html#replaceenum_
[BLOCH_2] Joshua Bloch, Effective Java,
Chapter 1, Item 1: Consider factory methods over constructors
[RFC2396] Uniform Resource Identifiers (URI):
Generic Syntax, _http://www.ietf.org/rfc/rfc2396.txt._
[JAX-RPC] Javaª API for XML-based RPC JAX-RPC
1.0, _http://java.sun.com/xml/downloads/jaxrpc.html_ .
[JAX-WS] Javaª API for XML Web
Services(JAX-WS) 2.0, Marc Hadley, Roberto Chinnici.
[JLS] or [JLS3] The Java Language
Specification, 3rd Edition, Gosling, Joy, Steele, Bracha. Available at
_http://java.sun.com/docs/books/jls_ .
[NIST] NIST XML Schema Test Suite, +
_http://xw2k.sdct.itl.nist.gov/xml/page4.html._
[MTOM] SOAP Message Transmission Optimization
Mechanism, http://www.w3.org/TR/2004/WD-soap12-mtom-20040608/
[XOP] Martin Gudgin, Noah Mendelsohn, Mark
Nottingham, and Herve Ruellan. XML-binary Optimized Packaging.
Recommendation, W3C, January 2005. http://www.w3.org/TR/xop10/.
[MIME] Anish Karmarkar, Ümit Yalçinalp,
"Describing Media Content of Binary Data in XML", W3C note,
http://www.w3.org/TR/2005/NOTE-xml-media-types-20050504
[WSIAP] Chris Ferris, Anish Karmarkar, and
Canyang Kevin Liu. Attachments Profile Version 1.0. Final 1 Material,
WS-I, August 2004.
http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html.
[WSIBP] WS-I Basic Profile 1.0,
http://www.ws-i.org/Profile/Basic/2003-08/BasicProfile-1.0a.html
[CA] Common Annotations for the Javaª
Platform, Rajiv Mordani
=== [[a3855]]Appendix
[[a3856]]Runtime Processing
=== Introduction
Two of the important goals of JAXB 2.0 are
portability (for inclusion in J2SE) and handling of invalid XML content
(for e.g. schema evolution). These goals imply that a JAXB Provider must
be capable of marshalling and unmarshalling XML instances using JAXB
annotated classes derived using another JAXB Provider. To ensure
portable behavior of JAXB mapped classes across JAXB Providers requires
a specification of runtime processing model of the JAXB 2.0 binding
framework.
This appendix specifies the runtime
processing model of XML instances and requirements on JAXB 2.0
Provider's runtime. It differs from the documentation found elsewhere in
the specification/javadocs. Chapter 4,”Binding Framework” and the
javadocs for the package jakarta.xml.bind do describe the JAXB 2.0 binding
framework. But these are written from a JAXB 2.0 developer perspective
rather than from a JAXB 2.0 Provider perspective and thus do not
describe requirements on JAXB 2.0 Provider runtime. This was sufficient
for JAXB 1.0 since portability was not a goal for JAXB 1.0 and schema
derived implementation classes were coupled to the JAXB 1.0 Provider
runtime. However, this is insufficient for JAXB 2.0, where portability
and handling invalid XML content are goals.
=== Scope and Conventions
=== Scope
This appendix describes marshalling and
unmarshalling.
=== Format
The specification uses the following for
specifying runtime behavior:
* XML Infoset, Second Edition,
http://www.w3.org/TR/xml-infoset augmented with attributes xsi:type and
xsi:nil that can be used by a document author.
* XML Schema abstract schema component model.
* JAXB defined annotations as needed
=== Notations
The following notations/conventions are used:
* For brevity, property is used but is used
to mean JavaBean property or a field.
* XML Infoset properties that are associated
with an information item are enclosed in [...], for e.g. AII.[local
name]. And program elements the constitute the Java representation to
which an information item are identified as for e.g. AII.valuetype.
* AII: Attribute Information Item in XML
Infoset
* AII.[local name] : local name property in
infoset for AII
* AII.[namespace] : namespace property in
infoset for AII
* AII.[owner element] : owner element in
infoset for AII
* AII.[normalized value]: normalized value in
inforset for AII
* AII.property : JAXB property to which AII
is mapped. The property in in the java type to which AII.[owner element]
is mapped.
* AII.valuetype: Java type representing the
XML serialized for AII.
* AII.boundtype: Java type that is bound;
this differs from AII.valuetype only if JAXB property is associated with
a @XmlJavaTypeAdapter.
* AII.schematype : schema type to which AII
is bound statically using Java -> XML schema mapping rules.
* EII: Element Information Item in infoset
* EII.[local name] : local name property in
XML infoset for EII
* EII.[namespace] : namespace property in XML
infoset for EII
* EII.[children]: children property in XML
infoset for EII
* EII.[parent]: parent property in XML
infoset for EII
* EII.property : JAXB property to which EII
is mapped. The property is in the javatype to which EII.[parent] is
mapped.
* EII.valuetype : java type representing the
XML serialized for EII
* EII.boundtype : java type that is bound;
this differs from EII.valuetype only if JAXB property is associated with
a @XmlJavaTypeAdapter.
* EII.schematype : schema type to which EII
is bound statically using java -> XML schema mapping rules.
* EII.xsitype : the xsi:type specified in the
XML instance by a document author. null if no xsi:type was specified.
* EII.xsinil : the xsi:nil specified in the
XML instance by a document author. null if no xsi:nil was specified.
=== Unmarshalling
This section specifies the runtime behavior
and JAXB provider requirements related to unmarshalling. The
specification includes unmarshalling of invalid XML content in an XML
instance. +
+
This section specifies only flexible, standard unmarshalling (flexible
because unmarshalling deals with invalid XML content). Other
unmarshalling modes will not be specified. Flexible unmarshalling
specified here must be supported by all JAXB Providers.
The unmarshalling methods in the binding
framework fall into the following categories:
. Unmarshal methods that do not take a
declaredType as parameter:
_jakarta.xml.bind.Unmarshaller.unmarshal_
(...) +
_jakarta.xml.bind.Binder.unmarshal_ (...) +
. Unmarshal methods that take a declaredType
as a parameter:
_jakarta.xml.bind.Unmarshaller.unmarshal_
(..., _java.lang.Class<T> declaredType_ ) +
_jakarta.xml.bind.Binder.unmashal_ (..., _java.lang.Class<T> declaredType_
)
The unmarshal methods that do not take
declaredType as parameter must be unmarshalled as specified in
link:jaxb.html#a3902[See Globally Declared Root Element]”.
The unmarshal methods that take a
_declaredType_ as a parameter must be unmarshalled as specified in
link:jaxb.html#a3953[See Declared Type]”.
=== [[a3902]]Globally Declared Root Element
There are two ways that a root element can be
represented in Java representation:
* as an element instance factory method that
is generated in the public ObjectFactory class of a package when a
schema is compiled. An element instance factory method is annotated with
a
@XmlElementDecl annotation. For e.g.
public class ObjectFactory \{
@XmlElementDecl(...)
public JAXBElement<T> createFoo(T
elementValue);
...
}
* as a type (either an enum type or a class)
that has been annotated with @XmlRootElement. For e.g.
@XmlRootElement(...)
public class Foo \{...}
The unmarshalling of XML content results in a
content tree with a root that is an instance of either a _JAXBElement_
instance or a type that is annotated with _@XmlRootElement_ . The
content tree must be created as follows:
. lookup an element factory method in the
ObjectFactory class matching on:
EII.[namespace] ==
@XmlElementDecl.namespace() && EII.[local name] ==
@XmlElementDecl.name()
or for a type annotated with @XmlRootElement
matching on:
EII.[namespace] ==
@XmlRootElement.namespace() && EII.[local name] ==
@XmlRootElement.name()
NOTE: The lookup will only find one of the
above not both. If both a type as well as an element factory method were
found, it would be flagged as an error when JAXBContext is created.
. if an element factory method in the
ObjectFactory class or a type annotated with @XmlRootElement is found,
then determine the valueType.
. if an element factory method is found,
there is no @XmlJavaTypeAdapter associated with the value parameter to
the element factory method, then the valueType is the java type of the
value parameter to the element factory method. For e.g.
@XmlElementDecl(name = "bar", namespace =
"")
public JAXBElement<Foo> createBar(Foo value)
\{
return new JAXBElement<Foo>(
_Bar_QNAME, ((Class) Foo.class), null,
value);
}
the valueType type is Foo.
*
if the parameter is associated with
@XmlJavaTypeAdapter, then the valueType is the java type specified in
@XmlJavaTypeAdapter.value() .
. if a type annotated with @XmlRootElement is
found then valueType is the type. For e.g.
@XmlRootElement(...)
public class Foo \{ ... }
*
Go to step 4, “Check for type substitution”
. If neither the element factory method nor a
type annotated with @XmlRootElement is found, then the element is
unknown. Set valueType of the element to null.
Even though the element is unknown, a
document author can still perform type substitution. This case can arise
if the XML schema contains only schema types and no global elements. For
e.g a document author could have specified a xsi:type that has been
mapped by JAXB. For e.g.
<unknownElement xsi:type="PurchaseOrder"/>
So goto step 4, "Check for type substitution"
. “Check for type substitution”
. if xsi:type is not specified, and the
valueType is null (i.e. the root element is unknown and we got to this
step from step 3), throw a _jakarta.xml.bind.UnmarshalException_ and
terminate processing.
. otherwise, if _xsi:type_ is specified, but
is not mapped to a JAXB mapped type (e.g. class is not marked with
@XmlType declaration), then throw a _jakarta.xml.bind.UnmarshalException_
and terminate processing.
. otherwise, if xsi:type is specified, and is
mapped to a JAXB mapped type set the valueType to the javatype to which
xsi:type is mapped.
. otherwise, xsi:type is not specified;
valueType is unchanged.
. Unmarshal valueType as specified in
link:jaxb.html#a3960[See Value Type]”.
. If the element factory method is annotated
with @XmlJavaTypeAdapter, then convert the valueType into a boundType
boundType =
@XmlJavaTypeAdapter.value().unmarshal(valueType)
. Determine the content root type to be
returned by unmarshal() method.
. if the element lookup returned an element
instance factory method, then create a JAXBElement instance using the
boundType. The content root type is the JAXBElement instance.
. otherwise, if the element lookup returned a
type annotated with @XmlRootElement, then the content root type is the
boundType.
. otherwise, the element is an unknown
element. Wrap the boundType using JAXBElement with an element name in
the XML instance document (e.g. “unknown Element”). The content root
type is the JAXBElement instance.
. return the content root type.
=== [[a3953]]Declared Type
The unmarshalling process described in this
section must be followed for the unmarshal methods that take a
_declaredType_ as a parameter.
. Determine the valueType to be unmarshalled
as follows:
. if _xsi:type_ is specified, but is not
mapped to a JAXB mapped type , then throw a
_jakarta.xml.bind.UnmarshalException_ and terminate processing.
. otherwise if _xsi:type_ is specified and is
mapped to JAXB mapped type, then valueType is the JAXB mapped type.
. otherwise valueType is the argument passed
to _declaredType_ parameter in the +
_unmarshal_ (..., _java.lang.Class<T>declaredType_ ) call.
. Unmarshal valueType as specified in
link:jaxb.html#a3960[See Value Type]”.
=== [[a3960]]Value Type
The following steps unmarshal either
EII.valuetype or AII.valuetype, depending upon whether an EII or AII is
being unmarshalled.
Note: Whether an EII or AII is being
unmarshalled is determined by the “caller” of this section.
AII.valuetype and EII.valuetype are assumed to be set by the time this
section entered.
. If an instance of valueType does not exist,
create an instance of valueType as follows (for e.g. if a value of a
property with type _java.util.List_ is non null, then unmarshal the
value into that _java.util.List_ instance __ rather than creating a new
instance of _java.util.List_ and assigning that to the property):
. if valueType is a class and is the type
parameter specified in the element factory method, then instantiate the
class using element factory method; otherwise instantiate the class
using factory method if specified by _@XmlType.factoryClass()_ and
_@XmlType.factoryMethod();_ or if there is no factory method, using the
no-arg constructor.
. if valueType is an enum type, then obtain
an instance of the enum type for the enum constant annotated with
_@XmlEnumValue_ and _@XmlEnumValue.value()_ matches the lexical
representation of the EII.
. Invoke any event callbacks in the following
order as follows:
. If valueType implements an unmarshal event
callback _beforeUnmarshal(..)_ as specified in Section 4.4.1,”Unmarshal
Event Callback”, then invoke _beforeUnmarshal(..)_ .
. If _Unmarshaller.getListener()_ returns
_Unmarshaller.Listener_ that is not null, then invoke
_Unmarshaller.Listener.beforeUnmarshal(..)_ .
. If an EII.valuetype is being unmarshalled,
unmarshal into this instance the following. Note: The following steps
can be done in any order; the steps are just broken down and listed
separately for clarity:
If EII.valueType being unmarshalled
. unmarshal each child element information
item in EII.[children] as specified in link:jaxb.html#a3978[See
Element Information Item]”.
. unmarshal each attribute information item
in EII.[attributes] as specified in link:jaxb.html#a4002[See
Attribute Information Item]”.
. Unmarshal the value of EII.schematype or
AII.schematype following the Java to XML Schema rules defined in Chapter
8, “Java Types to XML”. If the value in XML instance is unparseable,
then it must be handled as specified in link:jaxb.html#a4086[See
Unparseable Data for Simple types]”.
. Invoke any event callbacks in the following
order as follows:
. If valueType implements an unmarshal event
callback _afterUnmarshal(..)_ as specified in Section 4.4.1,”Unmarshal
Event Callback”, then invoke _afterUnmarshal(..)_ .
. If _Unmarshaller.getListener()_ returns
_Unmarshaller.Listener_ that is not null, then invoke
_Unmarshaller.Listener.afterUnmarshal(..)_ .
. return // either AII.valuetype or
EII.valuetype.
=== [[a3978]]Element Information Item
An EII must be unmarshalled as follows:
. infer EII.property as specified in
link:jaxb.html#a4023[See Property Inference - Element
Information Item]”.
. if EII.property is null, then there is no
property to hold the value of the element. If validation is on (i.e.
Unmarshaller.getSchema() is not null), then report a
jakarta.xml.bind.ValidationEvent. Otherwise, this will cause any unknown
elements to be ignored.
If EII.property is not null and there is no
setter method as specified in section link:jaxb.html#a4259[See
Getters/Setters]” then report a jakarta.xml.bind.ValidationEvent.
Goto step 8.
. infer the EII.valuetype as described in
link:jaxb.html#a4043[See Type Inference - Element Information
Item]”.
. if EII.valuetype is null, then go to step
8.
NOTE: EII.valuetype = null implies that there
was problem. so don't attempt to unmarshal the element.
. Unmarshal EII.valuetype as specified in
link:jaxb.html#a3960[See Value Type]”.
. if there is a @XmlJavaTypeAdapter
associated with EII.property, then adapt the EII.valuetype as follows:
EII.boundtype = +
@XmlJavaTypeAdapter.value().unmarshal(EII.valuetype)
otherwise
EII.boundtype = EII.valuetype
. set the value of EII.property to
EII.boundtype as follows:
Wrap EII.boundtype into a
jakarta.xml.bind.JAXBElement instance if:
. the property is not a collection type and
its type is jakarta.xml.bind.JAXBElement
. the property is a collection type and is a
collection of JAXBElement instances (annotated with @XmlElementRef or
@XmlElementRefs)
If EII.property is not a collection type:
. set the value of EII.property to
EII.boundtype.
If EII.property is collection type:
. add EII.boundtype to the end of the
collection.
NOTE: Adding JAXBElement instance or a type
to the end of the collection preserves document order. And document
order could be different from the order in XML Scheme if the instance
contains invalid XML content.
. return
=== [[a4002]]Attribute Information Item
An attribute information item must be
unmarshalled as follows:
. infer AII.property as described in section
link:jaxb.html#a4033[See Property Inference - Attribute
Information Item]”.
. if AII.property is null, then the attribute
is invalid with respect to the XML schema. This is possible if for e.g.
schema has evolved. If validation is on (i.e. Unmarshaller.getSchema()
is not null), then report a jakarta.xml.bind.ValidationEvent. Otherwise,
this will cause any unknown elements to be ignored.
If AII.property is not null and there is no
setter method as specified in section link:jaxb.html#a4259[See
Getters/Setters]” then report a jakarta.xml.bind.ValidationEvent. +
+
Goto step 8.
. infer the AII.valuetype as described in
link:jaxb.html#a4079[See Type Inference - Attribute Information
Item]”.
. if AII.valuetype is null, then go to step
8.
NOTE: AII.valuetype = null implies that there
was problem. so don't attempt to unmarshal the attribute.
. Unmarshal AII.valuetype as specified in
link:jaxb.html#a3960[See Value Type]”.
. If AII.property is associated with a
_@XmlJavaTypeAdapter_ , adapt AII.valuetype as follows:
AII.boundtype =
@XmlJavaTypeAdapter.value().unmarshal(AII.valuetype)
otherwise
AII.boundtype = AII.valuetype
. If AII.property is single valued:
. set the value of AII.property to
AII.boundtype.
If AII.property is a collection type (e.g.
List<Integer> was mapped to a Xml Schema list simple type using @XmlList
annotation):
add EII.boundtype to the end of the
collection.
. return
=== Property Inference
Unmarshalling requires the inference of a
property or a field that contains the value of EII and AII being
unmarshalled.
=== [[a4023]]Property Inference - Element Information Item
The property to which an EII is mapped is
inferred based on name.
*
Infer EII.property by matching constraints
described below:
. initialize EII.property to null
. if property is mapped to XML Schema element
declaration, elem, in the content model of EII.[parent].schematype &&
EII.[local name] == elem.\{name} && EII.[namespace] == elem.\{namespace}
set EII.property to property
Goto step 4.
. If there is a JAXB property mapped to XML
Schema wildcard ( _xs:any_ ) (as determined by _@XmlAnyElement_ ), set
this JAXB property to EII.property. This property will hold wildcard
content (e.g. invalid XML content caused by schema evolution).
. return EII.property
=== [[a4033]]Property Inference - Attribute Information Item
Infer the property for the AII by matching
constraints described below:
. initialize AII.property to null
. if property mapped to XML Schema attribute
declaration, attr, in the content model of AII.[owner].schematype &&
AII.[local name] == attr.\{name} && AII.[namespace] == attr.\{namespace}
set AII.property to property
Goto step 4.
. if there is a property mapped to a XML
Schema xs:anyAttribute (i.e. annotated with _@XmlAnyAttribute_ ), then
set this property to AII.property. This property holds XML content
matching wildcard attribute ( _xs:anyAttribute)_ or unknown attributes
(which can occur for e.g. if schema has evolved).
. return AII.property
=== Type Inference
Unmarshalling requires the inference of the
type of a property or a field that to contain the value of EII and AII
being unmarshalled.
=== [[a4043]]Type Inference - Element Information Item
This section describes how to infer
EII.valuetype; this holds the value of the element (content model +
attributes).
EII.valuetype must be inferred as described
below:
. initialize EII.valuetype to null.
. if EII.xsitype is set, document author has
performed type substitution.
Goto step 4 to handle type substitution.
. if EII.schematype is not mapped to a java
type, then
. report a validation event.
. Go to step 7.
otherwise
. set EII.valuetype to the javatype to which
EII.schematype is mapped.
. Go to step 7.
NOTE: This case can arise for example, when
EII.schematype is compiled into a java type at schema compilation time,
but the javatype was not registered with _JAXBContext.newInstance(..)_ .
. check if EII.xsitype is mapped to a JAXB
mapped type. It is possible that EII.xsitype is compiled to a javatype
at schema compilation time, but the javatype was not registered with
_JAXBContext.newInstance(..)_
If EII.xsitype is not mapped, then report a
validation event.
Goto step 7.
. check if the java type to which EII.xsitype
is mapped is assignment comparable with the static type of the
property/field if no _@XmlJavaTypeAdapter_ is associated with the
property/field or with the _valueType_ specified in
_XmlAdapter<valueType, boundType>_ if a _@XmlJavaTypeAdapter_ is
associated with the property/field.
The above check can fail for e.g when a
document author attempts to substitute a complex type that derives from
simple type but customization to enable simple type substitution was not
used. For e.g.
. <!-- local element with simple type -->
<xs:element name="foo" type="xs:int"/>
<!-- complex type for substituting the
simple type -->
<xs:complexType name="MyInt">
<xs:extension xs:int>
...add attributes
</xs:extends>
</xs:complexType>
. customization to handle type substitution
of simple types is not used. So the property is
public int getFoo();
public void setFoo(int );
public class MyInt \{...}
. the document author attempts to substitute
complexType MyInt.
<foo xsi:type="MyInt"/>
. The type MyInt is not assignment comparable
with int.
. set EII.valuetype to javatype to which
EII.xsitype is mapped.
NOTE: if we got to this step, this implies
that type substitution is valid.
. return EII.valuetype
=== [[a4079]]Type Inference - Attribute Information Item
Infer the AII.valuetype as follows:
. initialize AII.valuetype to null.
. if AII.schematype is not mapped to a java
type, then report a validation event. Otherwise, set AII.valuetype to
the java type to which AII.schematype is mapped.
NOTE: This case can arise for example, when
AII.schematype is compiled into a java type at schema compilation time,
but the javatype is not registered with the
_JAXBContext.newInstance(..)_
. return AII.valuetype
=== Invalid XML Content
=== [[a4086]]Unparseable Data for Simple types
If simple type data cannot be parsed into a
java datatype, then the value of the java datatype must not change the
current set value. An access to the datatype must return the value as
specified in link:jaxb.html#a4095[See Missing element
information item]”. If the conversion of lexical representation into a
value results in an exception, then the exception must be caught and a
validation event reported. This is to ensure that such conversion errors
do not terminate unmarshalling.
// Example : XML Schema fragment
<xs:element name="foo" type="xs:int"/>
// Example: XML instance.
// Data is not parseable into type xs:int ;
however unmarshal will
// still succeed.
<foo> SUN </foo>
=== [[a4095]]Missing element information item
This case arises when an element declaration
required by a XML schema is missing from the XML instance.
Property or field access must return the
value specified in link:jaxb.html#a4101[See Value for missing
elements/attributes]”
=== Missing Attribute
This case arises when a property or a field
is mapped to an XML attribute but the attribute is missing from the XML
instance.
Property or field access must return the
value specified in link:jaxb.html#a4101[See Value for missing
elements/attributes]”.
=== [[a4101]]Value for missing elements/attributes
If an attribute or an element is missing from
an XML instance, then unmarshal will not change the current set value.
An access to the property will return the set value or if unset, the
uninitialized value. The uninitialized value of the property or field
depends upon it's type. If the type is
. int - value is 0
. boolean - value is false
. a reference (must be mapped to a simple
type) - value is null.
. float - the value is +0.0f
. double - the value is 0.0d
. short - the value is (short) 0
. long - the value is 0L
Note The uninitialized values are returned
only if the value is not set. A value could be set for example in a
validation handler that catches the validation event.
=== Unknown Element
In this case, XML instance contains EII for
which there is no corresponding element declaration in the XML schema.
If the valuetype to which the EII.parent maps contains a property/field
annotated with _@XmlAnyElement_ , this EII can be unmarshalled into the
property/field.
Unknown attribute handling during
unmarshalling is specified in link:jaxb.html#a4023[See Property
Inference - Element Information Item]”.
=== Unknown attribute
In this case, XML instance contains AII for
which there is no corresponding attribute declaration in the XML schema.
If the valuetype to which the AII.parent maps contains a property/field
annotated with _@XmlAnyAttribute_ , the AII can be unmarshalled into the
property/field.
Unknown attribute handling during
unmarshalling is specified in link:jaxb.html#a4033[See Property
Inference - Attribute Information Item]”.
=== Marshalling
To marshal a content tree, a JAXB application
invokes one of the following marshal methods:
Marshaller.marshal(Object jaxbElement, ...)
throws JAXBException;
Binder.marshal(Object jaxbObject, ...) throws
JAXBException;
A JAXB Provider must marshal the content tree
as follows:
* marshal the XML root element tag as
specified in link:jaxb.html#a4125[See XML Root Element Tag]”
* marshal _obj_ as specified in section
link:jaxb.html#a4132[See Type]”.
=== [[a4125]]XML Root Element Tag
. If _obj_ is an instance of
_jakarta.xml.bind.JAXBElement_ then marshal _obj_ as specified in
link:jaxb.html#a4139[See JAXBElement]”
Goto step 4
. If _obj.getClass()_ is annotated with
_@XmlRootElement_ , then set \{EII.[local name], EII.[namespace]} by
deriving them from the @XmlRootElement annotation following the Java to
Schema mapping rules in chapter 8. Marshal obj instance as specified in
link:jaxb.html#a4132[See Type]”.
Goto step 4
. If obj has neither an @XmlRootElement nor
is a JAXBElement instance, then throw a _JAXBException_ and terminate
processing.
. done
=== [[a4132]]Type
The type must be marshalled as follows. If
the type is an instance of
* JAXBElement , then marshal as specified in
link:jaxb.html#a4139[See JAXBElement]”.
* Otherwise, marshal the type as follows. If
the type is a :
* class, then marshal as specified in
link:jaxb.html#a4156[See class]”.
* primitive type or standard class, then
marshal as specified in link:jaxb.html#a4180[See Primitives and
Standard classes]”
* enum type then marshal following the schema
to which it is mapped.
=== [[a4139]]JAXBElement
An _obj,_ that is an instance of
_jakarta.xml.bind.JAXBElement_ must be marshalled as specified here:
. _JAXBElement jaxbelem = (JAXBElement)
obj;_
. set \{EII.[local name] , EII.[namespace]}
to _jaxbelem.getName()_
. if _jaxbelem.isNil()_ , add _xsi:nil_ to
EII.[attributes]
.
. if _jaxbelem.isTypeSubstituted()_ is true,
then type substitution has occurred i.e. _jaxbelem.getDeclaredType()_
(static type) is different from _jaxbelem.getValue()_ (the type of the
value for this instance). So,
. EII.[local name] = “type”
. EII.[prefix]=”xsi”
. EII.[normalized value] = QName of the
schema type to which _jaxbelem.getValue()_ is mapped following Java ->
Schema mapping rules in Chapter 8. For e.g.
<foo xsi:type=”MyAddrType”/>
. set boundType to _jaxbelem.getValue()_ if
_jaxbelem.isTypeSubstituted()_ is _true_ otherwise
_jaxbelem.getDeclaredType()_
. determine the valueType to be marshalled.
If the program element being processed is associated with
@XmlJavaTypeAdapter then boundType is
valueType =
@XmlJavaTypeAdapter.value().marshal(boundType)
otherwise valueType is boundType
. map valueType to XML infoset information
items as specified in link:jaxb.html#a4132[See Type]” and add
them to EII.
. marshal EII.
=== [[a4156]]class
A class must be mapped to XML infoset items
as follows:
. If a class mapped to a value as specified
link:jaxb.html#a3331[See @XmlValue]”, then map the value to an
XML infoset and add it to EII.[children]
return
. For each property that is mapped to XML
attribute as specified in link:jaxb.html#a3230[See
@XmlAttribute]”:
. derive \{AII.[local name], AII.[prefix],
AII.[namespace] } from \{name} \{target namespace}.
. AII.[normalized value] = value of property
as specified in link:jaxb.html#a4169[See property type]”
. add AII to EII.[attributes]
NOTE: There order in which the properties are
marshalled is not specified (XML attributes are unordered by XML
Schema).
. For each property that is mapped to an XML
element declaration, elem:
. derive \{childEII.[local name],
childEII.[prefix], childEII.[namespace] } from elem.\{name}
elem.\{target namespace}
. map property type to XML infoset items into
childEII as specified in link:jaxb.html#a4169[See property
type]”.
. add childEII to EII.[children]
=== [[a4169]]property type
The value of a property with type ,
boundType, must be marshalled into childEII (set by “caller of this
section”) as follows:
. If property does not have a getter method
as specified in section link:jaxb.html#a4259[See
Getters/Setters]” then report a jakarta.xml.bind.ValidationEvent. Goto
step 4.
. If the value of the property being
marshalled is a subtype boundType, then
. EII.[local name] = “type”
. EII.[prefix]=”xsi”
. EII.[normalized value] = QName of the
schema type to which _jaxbelem.getValue()_ is mapped following Java ->
Schema mapping rules in Chapter 8. For e.g.
<foo xsi:type=”MyAddrType”/>
. add EII to childEII
. Marshal the value as specified in
link:jaxb.html#a4132[See Type]”.
. Return
=== [[a4180]]Primitives and Standard classes
Primitive values and standard classes
described in this section map to XML schema simple types.
The value of a primitive type or a standard
class must be marshalled to a lexical representation or unmarshalled
from a lexical representation as specified in the below:
* using a print or parse method in
jakarta.xml.bind.DatatypeConverter interface:
Many of the types have a corresponding print
and parse method in jakarta.xml.bind.DatatypeConverter interface for
converting a value to a lexical representation in XML and vice versa.
The implementation of DatatypeConverter is JAXB Provider specific.
A XML Schema simple type can have more than
lexical representation (e.g. “true” “false” “0” “1”). Since the
DatatypeConverter implementation is JAXB Provider specific, the exact
lexical representation that a value is marshalled to can vary from one
JAXB Provider to another. However, the lexical representation must be
valid with respect to the XML Schema.
* some data types such as
XMLGregorianCalendar contain methods on the class that return or consume
their XML lexical representation. For such datatypes, the method
indicated in the table is used.
* A wrapper class (e.g. java.lang.Integer)
must be converted to its non wrapper counterpart (e.g. int) and then
marshalled.
=== Lexical Representation of Standard Classes
Java Standard Classes
printMethod
parse Method
_java.lang.String_
_printString_
_parseString_
_java.util.Calendar_
_printDateTime_
_parseDateTime_
_java.util.Date_
_printDateTime_
_parseDateTime_
_java.net.URI_
_URI.toString()_
_URI(String str)_
_javax.xml.datatype._
_XMLGregorianCalendar_
_XMLGregorianCalendar._
_toXMLFormat()_
_DatatypeFactory._
_newXMLGregorianCalendar(_
_String lexicalRepresentation)_
_javax.xml.datatype._
_Duration_
_Duration._
_toString()_
_DatatypeFactory._
_newDuration(_
_String lexicalRepresentation)_
_java.util.UUID_
_UUID.toString()_
_UUID.fromString()_
=== Null Value
A null value in Java representation can be
marshalled either as an absence of an element from an XML instance or as
_xsi:nil_ . The marshalled value depends upon the values of
_@XmlElement.required()_ and _@XmlElement.nillable()_ annotation
elements on the property/field and must be marshalled as shown below.
For clarity, example schema fragments (as determined by the mapping
rules specified in Chapter 8) for the following field
@XmlElement(required=”..”, nillable=”...”)
foo;
are reproduced here along with the XML
representation for null value produced by marshalling.
* _@XmlElement(required=true, nillable_ =
_false)_
The value of the property/field cannot be
null.
// Example: generated schema
<xs:element name=”foo” minOccurs=”1”/ ...>
...
</xs:element>
* _@XmlElement(required=true,
nillable=true)_
null is marshalled as _xsi:nil=”true”_
// Example:generated schema
<xs:element name=”foo” minOccurs=”1”
nillable=”true” ...>
...
/xs:element>
<!-- marshalled XML representation for null
value -->
<foo xsi:nil=”true” .../>
* _@XmlElement(required=false,
nillable=true)_
null is marshalled as _xsi:nil=”true”_
// Examle: generated schema
<xs:element name=”foo” minOccurs=”0” ...>
...
</xs:element>
<!-- Example: marshalled XML representation
for null value -->
<foo xsi:nil=”true” .../>
* _@XmlElement(required=false,
nillable=false)_
null is not marshalled i.e it maps to absence
of an element from XML instance.
// Example: Generated schema
<xs:element name=”foo” minOccurs=”0” ...>
...
</xs:element>
<!-- Example: null value for foo not
marshalled -->
=== [[a4259]]Getters/Setters
When _@XmlAccessType.PUBLIC_MEMBER_ or
_@XmlAccessType.PROPERTY_ is in effect for a class, then the instance of
the class is marshalled using getter/setter methods as opposed to
fields. This section outlines the constraints the must be checked at
runtime. A constraint failure is handled as specified elsewhere in the
chapter from where this section is referenced.
Unmarshalling : A property must have a setter
method if
* _@XmlAccessorType.PUBLIC_MEMBER_ or
_@XmlAccessorType.PROPERTY_ applies to the property.
* or if the property’s getter/setter method
is annotated with a mapping annotation.
The one exception to the above constraint is:
if property type is _java.util.List_ then only a getter method is
required.
*
Marshalling: A property must have a getter
method if
* _@XmlAccessType.PUBLIC_MEMBER_ or
_@XmlAccessType.PROPERTY_ applies to the class
* or if the property’s getter/setter method
is annotated with a mapping annotation.
=== Appendix
[[a4270]]Normative Binding Schema
Syntax
=== JAXB Binding Schema
Online versions of JAXB Binding Schema are
available at:
_http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd[]http://java.sun.com/xml/ns/jaxb/bindingschema_1_0.xsd[http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd +
http://java.sun.com/xml/ns/jaxb/bindingschema_1_0.xsd +
]_
Additions to JAXB 1.0 binding schema are in
_bold_ .
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema
targetNamespace =
"http://java.sun.com/xml/ns/jaxb"
xmlns:jaxb =
"http://java.sun.com/xml/ns/jaxb"
xmlns:xs =
"http://www.w3.org/2001/XMLSchema"
elementFormDefault = "qualified" +
attributeFormDefault = "unqualified">
<xs:group name = "declaration">
<xs:choice>
<xs:element ref = "jaxb:globalBindings"/>
<xs:element ref = "jaxb:schemaBindings"/>
<xs:element ref = "jaxb:class"/>
<xs:element ref = "jaxb:property"/>
<xs:element ref = "jaxb:typesafeEnumClass"/>
<xs:element ref =
"jaxb:typesafeEnumMember"/>
<xs:element ref = "jaxb:javaType"/>
<xs:element ref = "jaxb:dom"/>
<xs:element ref = "jaxb:inlineBinaryData"/>
<xs:any namespace = "##other"
processContents = "lax"/>
</xs:choice>
</xs:group>
<xs:attribute name = "version"
type="xs:token" >
_<xs:annotation><xs:documentation>_
_Used to specify the version of the binding
schema on the schema element for inline annotations or jaxb:bindings for
external binding._
_</xs:documentation></xs:annotation>_
</xs:attribute>
<xs:attributeGroup name =
"propertyAttributes">
_<xs:annotation>_
_<xs:documentation>_
_Attributes used for property customization.
The attribute group can be referenced either from the globalBindings
declaration or from the_
_property declaration. The following
defaults are defined by the JAXB specification in global scope only.
Thus they apply when the propertyAttributes group is referenced from the
globalBindings declaration but not when referenced from the property
declaration._
_collectionType a class that implements
java.util.List._
_fixedAttributeAsConstantProperty false_
_enableFailFastCheck false_
_generateIsSetMethod false_
__ _optionalProperty wrapper_
_generateElementProperty false_
_</xs:documentation>_
_</xs:annotation>_
<xs:attribute name = "collectionType"
type="jaxb:referenceCollectionType"/>
<xs:attribute name =
"fixedAttributeAsConstantProperty" type = "xs:boolean"/>
<xs:attribute name = "enableFailFastCheck"
type = "xs:boolean"/>
<xs:attribute name = "generateIsSetMethod"
type = "xs:boolean"/>
_<xs:attribute name = "optionalProperty">_
_<xs:simpleType>_
_<xs:restriction base="xs:NCName">_
_<xs:enumeration value="wrapper"/>_
_<xs:enumeration value="primitive"/>_
_<xs:enumeration value="isSet"/>_
_</xs:restriction>_
_</xs:simpleType>_
_</xs:attribute>_
_<xs:attribute name =
"generateElementProperty" type="xs:boolean"/>_
</xs:attributeGroup>
<xs:attributeGroup name =
"XMLNameToJavaIdMappingDefaults">
_<xs:annotation>_
_<xs:documentation>Customize XMLNames to
Java id mapping</xs:documentation>_
_</xs:annotation>_
<xs:attribute name = "underscoreBinding"
default = "asWordSeparator" type = "jaxb:underscoreBindingType"/>
</xs:attributeGroup>
<xs:attributeGroup name =
"typesafeEnumClassDefaults">
<xs:attribute name =
"typesafeEnumMemberName" _default = "skipGeneration"_ type =
"jaxb:typesafeEnumMemberNameType"/>
<xs:attribute name = "typesafeEnumBase"
_default = "xs:string"_ type = "jaxb:typesafeEnumBaseType"/>
_<xs:attribute name =
"typesafeEnumMaxMembers" type="xs:int" default="256"/>_
</xs:attributeGroup>
<xs:element name = "globalBindings">
_<xs:annotation>_
_<xs:documentation>Customization values
defined in global scope.</xs:documentation>_
_</xs:annotation>_
<xs:complexType>
<xs:sequence minOccurs = "0"> +
<xs:element ref = "jaxb:javaType" minOccurs = "0" maxOccurs =
"unbounded"/> +
_<xs:element ref = "jaxb:serializable" minOccurs = "0"/>_
<xs:any namespace = "##other"
processContents = "lax">
_<xs:annotation> <xs:documentation>_
_allows extension binding declarations to be
specified._
_</xs:documentation></xs:annotation>_
</xs:any>
</xs:sequence>
<xs:attributeGroup ref =
"jaxb:XMLNameToJavaIdMappingDefaults"/>
<xs:attributeGroup ref =
"jaxb:typesafeEnumClassDefaults"/>
<xs:attributeGroup ref =
"jaxb:propertyAttributes"/>
_<xs:attribute name="generateValueClass"
type="xs:boolean"_
_default= "true"/>_
_<xs:attribute name="generateElementClass"
type="xs:boolean"_
_default= "false"/>_
_<xs:attribute name="mapSimpleTypeDef"
type="xs:boolean"_
_default= "false"/>_
_<xs:attribute name="localScoping" default=
"nested">_
_<xs:simpleType>_
_<xs:restriction base="xs:NCName">_
_<xs:enumeration value="nested"/>_
_<xs:enumeration value="toplevel"/>_
_</xs:restriction>_
_</xs:simpleType>_
_</xs:attribute>_
<xs:attribute name =
"enableJavaNamingConventions" default = "true" type = "xs:boolean"/>
<xs:attribute name = "choiceContentProperty"
default = "false" type = "xs:boolean"/>
</xs:complexType>
</xs:element>
<xs:element name = "schemaBindings">
<xs:annotation>
<xs:documentation>Customization values with
schema scope<xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:all>
<xs:element name = "package" type =
"jaxb:packageType" minOccurs = "0"/>
<xs:element name = "nameXmlTransform" type =
"jaxb:nameXmlTransformType" minOccurs = "0"/>
</xs:all>
</xs:complexType>
</xs:element>
<xs:element name = "class">
_<xs:annotation>_
_<xs:documentation>Customize interface and
implementation class.</xs:documentation>_
_</xs:annotation>_
<xs:complexType>
<xs:sequence>
<xs:element name = "javadoc" type =
"xs:string" minOccurs = "0"/>
</xs:sequence>
<xs:attribute name = "name" type =
"jaxb:javaIdentifierType">
_<xs:annotation>_
_<xs:documentation>Java class name without
package prefix.</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
<xs:attribute name = "implClass" type =
"jaxb:javaIdentifierType">
_<xs:annotation>_
_<xs:documentation>Implementation class name
including package prefix. </xs:documentation>_
_</xs:annotation>_
</xs:attribute>
_<xs:attribute name="generateValueClass"
type="xs:boolean" default= "true"/>_
</xs:complexType>
</xs:element>
<xs:element name = "property">
_<xs:annotation>_
_<xs:documentation>Customize
property.</xs:documentation>_
_</xs:annotation>_
<xs:complexType>
<xs:all>
<xs:element name = "javadoc" type =
"xs:string" minOccurs="0"/>
<xs:element name = "baseType"
type="jaxb:propertyBaseType" minOccurs="0"/>
</xs:all>
_<xs:attribute name = "name" type =
"jaxb:javaIdentifierType"/> +
<xs:attribute name = "attachmentRef" default="default">_
_<xs:simpleType>_
_<xs:restriction base="xs:NCName">_
_<xs:enumeration value="resolve"/>_
_<xs:enumeration value="doNotResolve"/>_
_<xs:enumeration value="default"/>_
_</xs:restriction>_
_</xs:simpleType>_
_</xs:attribute>_
<xs:attributeGroup ref =
"jaxb:propertyAttributes"/>
</xs:complexType>
</xs:element>
<xs:element name = "javaType">
_<xs:annotation>_
_<xs:documentation>Data type conversions;
overriding builtins</xs:documentation>_
_</xs:annotation>_
<xs:complexType>
<xs:attribute name = "name" use = "required"
type = "jaxb:javaIdentifierType">
_<xs:annotation>_
_<xs:documentation>name of the java type to
which xml type is to be bound.</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
<xs:attribute name = "xmlType" type =
"xs:QName">
_<xs:annotation>_
_<xs:documentation> xml type to which java
datatype has to be bound._
_Must be present when javaType is scoped to
globalBindings._
_</xs:documentation>_
</xs:annotation>
</xs:attribute>
<xs:attribute name = "parseMethod" type =
"jaxb:javaIdentifierType"/>
<xs:attribute name = "printMethod" type =
"jaxb:javaIdentifierType"/>
_<xs:annotation>_
_<xs:documentation>_
_If true, the parsMethod and printMethod
must reference a method_
_signtature that has a second parameter of
type NamespaceContext._
_</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name = "typesafeEnumClass">
_<xs:annotation>_
_<xs:documentation> Bind to a type safe
enumeration class.</xs:documentation>_
_</xs:annotation>_
<xs:complexType>
<xs:sequence>
<xs:element name = "javadoc" type =
"xs:string" minOccurs = "0"/>
<xs:element ref = "jaxb:typesafeEnumMember"
minOccurs = "0" maxOccurs = "unbounded"/>
</xs:sequence>
<xs:attribute name = "name" type =
"jaxb:javaIdentifierType"/>
_<xs:attribute name = "map" type =
"xs:boolean" default = "true"/>_
</xs:complexType>
</xs:element>
<xs:element name = "typesafeEnumMember">
_<xs:annotation>_
_<xs:documentation> Enumeration member name
in a type safe enumeration class.</xs:documentation>_
_</xs:annotation>_
<xs:complexType>
<xs:sequence>
<xs:element name = "javadoc" type =
"xs:string" minOccurs = "0"/>
</xs:sequence>
<xs:attribute name = "value"
type="xs:anySimpleType"/>
<xs:attribute name = "name" use = "required"
type = "jaxb:javaIdentifierType"/>
</xs:complexType>
</xs:element>
_<!-- TYPE DEFINITIONS -->_
<xs:complexType name = "propertyBaseType">
<xs:all>
<xs:element ref = "jaxb:javaType" minOccurs
= "0"/>
</xs:all>
_<xs:attribute name = "name" type =
"jaxb:javaIdentifierType">_
_<xs:annotation><xs:documentation>_
_The name attribute for [baseType] enables
more precise control over the actual base type for a JAXB property. This
customization enables specifying a more general/specialized base type
than the property's default base type. The name attribute value must be
a fully qualified Java class name. Additionally, this Java class must be
a super interface/class or subclass of the default Java base type for
the property. When the default base type is a primitive type, consider
the default Java base type to be the Java wrapper class of that
primitive type.This customization is useful to enable simple type
substitution for a JAXB property representing with too restrictive of a
default base type. It also can be used to provide stronger typing for
the binding of an element/attribute of type xs:IDREF._
_</xs:documentation></xs:annotation>_
_</xs:attribute>_
</xs:complexType>
<xs:complexType name = "packageType">
<xs:sequence>
<xs:element name = "javadoc" type =
"xs:string" minOccurs = "0"/>
</xs:sequence>
<xs:attribute name = "name" type =
"jaxb:javaIdentifierType"/>
</xs:complexType>
<xs:simpleType name =
"underscoreBindingType">
_<xs:annotation>_
_<xs:documentation> +
Treate underscore in XML Name to Java identifier mapping. +
</xs:documentation>_
_</xs:annotation>_
<xs:restriction base = "xs:string">
<xs:enumeration value = "asWordSeparator"/>
<xs:enumeration value = "asCharInWord"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name =
"typesafeEnumBaseType">
_<xs:annotation>_
_<xs:documentation> +
XML types or types derived from them which have enumeration facet(s)
which are be mapped to typesafeEnumClass by default. The following types
cannot be specified in this list: "xsd:QName", "xsd:base64Binary",
"xsd:hexBinary", "xsd:date", "xsd:time", "xsd:dateTime",
"xsd:duration","xsd:gDay", "xsd:gMonth", "xsd:Year", "xsd:gMonthDay",
"xsd:gYearMonth",_ _"xsd:ID", "xsd:IDREF", "xsd:NOTATION"_
_</xs:documentation>_
_</xs:annotation>_
<xs:list itemType = "xs:QName"/>
</xs:simpleType>
<xs:simpleType name =
"typesafeEnumMemberNameType">
_<xs:annotation><xs:documentation> +
Used to customize how to handle name collisions._
_</xs:documentation></xs:annotation>_
<xs:restriction base = "xs:string">
<xs:enumeration value = "generateName"/>
<xs:enumeration value = "generateError"/>
_<xs:enumeration value = "skipGeneration"/>_
</xs:restriction>
</xs:simpleType>
<xs:simpleType name = "javaIdentifierType">
_<xs:annotation>_
_<xs:documentation>Placeholder type to
indicate Legal Java identifier.</xs:documentation>_
_</xs:annotation>_
<xs:list itemType = "xs:NCName"/>
</xs:simpleType>
<xs:complexType name =
"nameXmlTransformRule">
_<xs:annotation>_
_<xs:documentation>Rule to transform an Xml
name into another Xml name</xs:documentation>_
_</xs:annotation>_
<xs:attribute name = "prefix" type =
"xs:string">
_<xs:annotation>_
_<xs:documentation>prepend the string to
QName.</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
<xs:attribute name = "suffix" type =
"xs:string">
_<xs:annotation>_
_<xs:documentation>Append the string to
QName.</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
</xs:complexType>
<xs:complexType name =
"nameXmlTransformType">
_<xs:annotation><xs:documentation>_
_Allows transforming an xml name into
another xml name. Use case UDDI 2.0
schema.</xs:documentation></xs:annotation>_
<xs:all>
<xs:element name = "typeName" type =
"jaxb:nameXmlTransformRule" minOccurs = "0">
_<xs:annotation><xs:documentation>Mapping
rule for type definitions.</xs:documentation></xs:annotation>_
</xs:element>
<xs:element name = "elementName" type =
"jaxb:nameXmlTransformRule" minOccurs = "0">
_<xs:annotation><xs:documentation>Mapping
rule for elements</xs:documentation></xs:annotation>_
</xs:element>
<xs:element name = "modelGroupName" type =
"jaxb:nameXmlTransformRule" minOccurs = "0">
_<xs:annotation>_
_<xs:documentation>Mapping rule for model
group</xs:documentation>_
_</xs:annotation>_
</xs:element>
<xs:element name = "anonymousTypeName" type
= "jaxb:nameXmlTransformRule" minOccurs = "0">
_<xs:annotation>_
_<xs:documentation>Mapping rule for class
names generated for an anonymous type.</xs:documentation>_
_</xs:annotation>_
</xs:element>
</xs:all>
</xs:complexType>
<xs:attribute name =
"extensionBindingPrefixes">
_<xs:annotation>_
_<xs:documentation>_
_A schema compiler only processes this
attribute when it occurs on an_
_an instance of xs:schema element. The value
of this attribute is a_
_whitespace-separated list of namespace
prefixes. The namespace bound_
_to each of the prefixes is designated as a
customization declaration_
_namespace._
_</xs:documentation>_
_</xs:annotation>_
<xs:simpleType>
<xs:list itemType = "xs:normalizedString"/>
</xs:simpleType>
</xs:attribute>
<xs:element name = "bindings">
_<xs:annotation>_
_<xs:documentation> +
Binding declaration(s) for a remote schema. If attribute node is set,
the binding declaraions are associated with part of the remote schema
designated by schemaLocation attribute. The node attribute identifies
the node in the remote schema to associate the binding declaration(s)
with._
_</xs:documentation>_
_</xs:annotation>_
_<!-- a <bindings> element can contain
arbitrary number of binding declarations or nested <bindings> elements
-->_
<xs:complexType>
<xs:sequence>
<xs:choice minOccurs = "0" maxOccurs =
"unbounded">
<xs:group ref = "jaxb:declaration"/>
<xs:element ref = "jaxb:bindings"/>
</xs:choice>
</xs:sequence>
<xs:attribute name = "schemaLocation" type =
"xs:anyURI">
_<xs:annotation>_
_<xs:documentation>_
_Location of the remote schema to associate
binding declarations with._
_</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
<xs:attribute name = "node" type =
"xs:string">
_<xs:annotation>_
_<xs:documentation>_
_The value of the string is an XPATH 1.0
compliant string that resolves to a node in a remote schema to associate
binding declarations with. The remote schema is specified by the
schemaLocation attribute occuring in the current element or in a parent
of this element. </xs:documentation>_
_</xs:annotation>_
</xs:attribute>
<xs:attribute name = "version" type =
"xs:token">
_<xs:annotation>_
_<xs:documentation>_
_Used to indicate the version of binding
declarations. Only valid on root level bindings element. Either this or
"jaxb:version" attribute but not both may be specified.
</xs:documentation>_
_</xs:annotation>_
</xs:attribute>
<xs:attribute ref = "jaxb:version">
_<xs:annotation>_
_<xs:documentation>_
_Used to indicate the version of binding
declarations. Only valid on root level bindings element. Either this
attribute or "version" attribute but not both may be
specified.</xs:documentation>_
_</xs:annotation>_
_</xs:attribute>_
</xs:complexType>
</xs:element>
<xs:simpleType
name="referenceCollectionType">
<xs:union>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="indexed"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType>
<xs:restriction
base="jaxb:javaIdentifierType"/>
</xs:simpleType>
</xs:union>
</xs:simpleType>
_<xs:element name="dom">_
_<xs:complexType>_
_<xs:attribute name = "type"
type="xs:NCName" default="w3c">_
_<xs:annotation><xs:documentation>Specify
DOM API to bind to JAXB property to.<xs:documentation></xs:annotation>_
_</xs:attribute>_
_</xs:complexType>_
_</xs:element>_
_<xs:element name="inlineBinaryData">_
_<xs:annotation> <xs:documentation> +
Disable MTOM/XOP encoding for this binary data. Annotation can be placed
on a type defintion that derives from a W3C XSD binary data type or on
an element that has a type that is or derives from a W3C XSD binary data
type._
_</xs:documentation></xs:annotation>_
_</xs:element>_
_<xs:element name = "serializable">_
_<xs:complexType>_
_<xs:attribute name="uid" type="xs:long"
default="1"/> +
</xs:complexType>_
_</xs:element>_
</xs:schema>
=== [[a4649]]Appendix
Binding XML Names to Java
Identifiers
=== Overview
This section provides default mappings from:
* XML Name to Java identifier
* Model group to Java identifier
* Namespace URI to Java package name
=== [[a4656]]The Name to Identifier Mapping Algorithm
Java identifiers typically follow three
simple, well-known conventions:
* Class and interface names always begin with
an upper-case letter. The remaining characters are either digits,
lower-case letters, or upper-case letters. Upper-case letters within a
multi-word name serve to identify the start of each non-initial word, or
sometimes to stand for acronyms.
* Method names and components of a package
name always begin with a lower-case letter, and otherwise are exactly
like class and interface names.
* Constant names are entirely in upper case,
with each pair of words separated by the underscore character (‘_’,
\u005F, LOW LINE).
XML names, however, are much richer than Java
identifiers: They may include not only the standard Java identifier
characters but also various punctuation and special characters that are
not permitted in Java identifiers. Like most Java identifiers, most XML
names are in practice composed of more than one natural-language word.
Non-initial words within an XML name typically start with an upper-case
letter followed by a lower-case letter, as in Java language, or are
prefixed by punctuation characters, which is not usual in the Java
language and, for most punctuation characters, is in fact illegal.
In order to map an arbitrary XML name into a
Java class, method, or constant identifier, the XML name is first broken
into a _word list_ . For the purpose of constructing word lists from XML
names we use the following definitions:
* A _punctuation character_ is one of the
following:
* A hyphen (’-’, \u002D, HYPHEN-MINUS),
* A period (‘.’, \u002E, FULL STOP),
* A colon (’:’, \u003A, COLON),
* A dot (‘.’, \u00B7, MIDDLE DOT),
* \u0387, GREEK ANO TELEIA,
* \u06DD, ARABIC END OF AYAH, or
* \u06DE, ARABIC START OF RUB EL HIZB.
* An underscore (’_’, \u005F, LOW LINE) with
following exceptionlink:#a5380[29]
These are all legal characters in XML names.
* A _letter_ is a character for which the
_Character.isLetter_ method returns _true_ , _i.e._ , a letter according
to the Unicode standard. Every letter is a legal Java identifier
character, both initial and non-initial.
* A _digit_ is a character for which the
_Character.isDigit_ method returns _true_ , _i.e._ , a digit according
to the Unicode Standard. Every digit is a legal non-initial Java
identifier character.
* A _mark_ is a character that is in none of
the previous categories but for which the
_Character.isJavaIdentifierPart_ method returns _true_ . This category
includes numeric letters, combining marks, non-spacing marks, and
ignorable control characters.
Every XML name character falls into one of
the above categories. We further divide letters into three
subcategories:
* An _upper-case letter_ is a letter for
which the _Character.isUpperCase_ method returns _true_ ,
* A _lowercase letter_ is a letter for which
the _Character.isLowerCase_ method returns _true_ , and
* All other letters are _uncased_ .
An XML name is split into a word list by
removing any leading and trailing punctuation characters and then
searching for _word breaks_ . A word break is defined by three regular
expressions: A prefix, a separator, and a suffix. The prefix matches
part of the word that precedes the break, the separator is not part of
any word, and the suffix matches part of the word that follows the
break. The word breaks are defined as:
=== [[a4681]]XML Word Breaks
Prefix
Separator
Suffix
Example
{empty}[^punct]
punct+1
{empty}[^punct]
foo|--|bar
digit
{empty}[^ _digit_ ]
foo|22|bar
{empty}[^digit]
digit
foo|22
lower
{empty}[^lower]
foo|Bar
upper
upper lower
FOO|Bar
letter
{empty}[^letter]
Foo|\u2160
{empty}[^letter]
letter
\u2160|Foo
uncased
{empty}[^uncased]
{empty}[^uncased]
uncased
(The character _\u2160_ is ROMAN NUMERAL ONE,
a numeric letter.)
After splitting, if a word begins with a
lower-case character then its first character is converted to upper
case. The final result is a word list in which each word is either
* A string of upper- and lower-case letters,
the first character of which is upper case (includes underscore,’_’, for
exception case1).
* A string of digits, or
* A string of uncased letters and marks.
Given an XML name in word-list form, each of
the three types of Java identifiers is constructed as follows:
* A class or interface identifier is
constructed by concatenating the words in the list,
* A method identifier is constructed by
concatenating the words in the list. A prefix verb ( _get_ , _set_ ,
_etc._ ) is prepended to the result.
* A constant identifier is constructed by
converting each word in the list to upper case; the words are then
concatenated, separated by underscores.
This algorithm will not change an XML name
that is already a legal and conventional Java class, method, or constant
identifier, except perhaps to add an initial verb in the case of a
property access method.
To improve user experience with default
binding, the automated resolution of frequent naming collision is
specified in link:jaxb.html#a4770[See Standardized Name
Collision Resolution]“.
=== Example
=== [[a4734]]XML Names and derived Java Class, Method, and Constant Names
XML Name
Class Name
Method Name
Constant Name
mixedCaseName
MixedCaseName
getMixedCaseName
MIXED_CASE_NAME
Answer42
Answer42
getAnswer42
ANSWER_42
name-with-dashes
NameWithDashes
getNameWithDashes
NAME_WITH_DASHES
other_punct-chars
OtherPunctChars
getOtherPunctChars
OTHER_PUNCT_CHARS
=== [[a4755]]XML Names and derived Java Class, Method, and Constant Names when <jaxb:globalBindings underscoreHandling=”asCharInWord”>
[width="100%",cols="25%,25%,25%,25%",options="header",]
|===
|XML Name |Class
Name |Method Name
|Constant Name
|other_punct-chars
|Other_punctChars
|getOther_punctChars
|OTHER_PUNCT_CHARS
|name_with_underscore
|Name_with_underscore
|name_with_underscore
|NAME_WITH_UNDERSCORE
|===
=== [[a4767]]Collisions and conflicts
It is possible that the name-mapping
algorithm will map two distinct XML names to the same word list.These
cases will result in a _collision_ if, and only if, the same Java
identifier is constructed from the word list and is used to name two
distinct generated classes or two distinct methods or constants in the
same generated class. It is also possible if two or more namespaces are
customized to map to the same Java package, XML names that are unique
due to belonging to distinct namespaces could mapped to the same Java
Class identifier. Collisions are not permitted by the schema compiler
and are reported as errors; they may be repaired by revising XML name
within the source schema or by specifying a customized binding that maps
one of the two XML names to an alternative Java identifier.
A class name must not conflict with the
generated JAXB class, _ObjectFactory_ , link:jaxb.html#a482[See
Java Package], that occurs in each schema-derived Java package. Method
names are forbidden to conflict with Java keywords or literals, with
methods declared in _java.lang.Object_ , or with methods declared in the
binding-framework classes. Such conflicts are reported as errors and may
be repaired by revising the appropriate schema or by specifying an
appropriate customized binding that resolves the name collision.
=== [[a4770]]Standardized Name Collision Resolution
Given the frequency of an XML element or
attribute with the name “class” or “Class” resulting in a naming
collision with the inherited method _java.lang.Object.getClass()_ ,
method name mapping automatically resolves this conflict by mapping
these XML names to the java method identifier “getClazz”.
*
=== [[a4773]]Deriving a legal Java identifier from an enum facet value
Given that an enum facet’s value is not
restricted to an XML name, the XML Name to Java identifier algorithm is
not applicable to generating a Java identifier from an enum facet’s
value. The following algorithm maps an enum facet value to a valid Java
constant identifier name.
* For each character in enum facet value, +
copy the character to a string representation _javaId_ when
_java.lang.Character.isJavaIdentifierPart()_ is _true_ .
* To follow Java constant naming convention,
each valid lower case character must be copied as its upper case
equivalent.
* There is no derived Java constant
identifier when any of the following occur:
* _javaId.length() == 0_
*
_java.lang.Character.isJavaIdentifierStart(javaId.get(0)) == false_
=== [[a4780]]Deriving an identifier for a model group
XML Schema has the concept of a group of
element declarations. Occasionally, it is convenient to bind the
grouping as a Java content property or a Java value class. When a
semantically meaningful name for the group is not provided within the
source schema or via a binding declaration customization, it is
necessary to generate a Java identifier from the grouping. Below is an
algorithm to generate such an identifier.
A name is computed for an unnamed model group
by concatenating together the first 3 element declarations and/or
wildcards that occur within the model group. Each XML \{name} is mapped
to a Java identifier for a method using the XML Name to Java Identifier
Mapping algorithm. Since wildcard does not have a \{name} property, it
is represented as the Java identifier “ _Any_ ”. The Java identifiers
are concatenated together with the separator “ _And_ ” for sequence and
all compositor and “ _Or_ ” for choice compositors. For example, a
sequence of element _foo_ and element _bar_ would map to _“_ _FooAndBar_
_”_ and a choice of element _foo_ and element _bar_ maps to _“_
_FooOrBar_ _._ ” Lastly, a sequence of wildcard and element _bar_ would
map to the Java identifier _“_ _AnyAndBar_ _”_ .
=== Example:
Given XML Schema fragment:
<xs:choice> +
<xs:sequence> +
<xs:element ref="A"/> +
<xs:any processContents="strict"/> +
</xs:sequence> +
<xs:element ref="C"/>
</xs:choice>
The generated Java identifier would be
_AAndAnyOrC_ .
=== [[a4788]]Generating a Java package name
This section describes how to generate a
package name to hold the derived Java representation. The motivation for
specifying a default means to generate a Java package name is to
increase the chances that a schema can be processed by a schema compiler
without requiring the user to specify customizations.
If a schema has a target namespace, the next
subsection describes how to map the URI into a Java package name. If the
schema has no target namespace, there is a section that describes an
algorithm to generate a Java package name from the schema filename.
=== Mapping from a Namespace URI
An XML namespace is represented by a URI.
Since XML Namespace will be mapped to a Java package, it is necessary to
specify a default mapping from a URI to a Java package name. The URI
format is described in [RFC2396].
The following steps describe how to map a URI
to a Java package name. The example URI,
_http://www.acme.com/go/espeak.xsd_ , is used to illustrate each step.
. Remove the scheme and _":"_ part from the
beginning of the URI, if present. +
Since there is no formal syntax to identify the optional URI scheme,
restrict the schemes to be removed to case insensitive checks for
schemes “ _http_ ” and “ _urn_ ”.
_//www.acme.com/go/espeak.xsd_
. Remove the trailing file type, one of _.??_
or _.???_ or _.html_ .
_//www.acme.com/go/espeak_
. Parse the remaining string into a list of
strings using _’/’_ and _‘:’_ as separators. Treat consecutive
separators as a single separator.
_\{"www.acme.com", "go", "espeak" }_
. For each string in the list produced by
previous step, unescape each escape sequence octet.
_\{"www.acme.com", "go", "espeak" }_
. If the scheme is a “urn”, replace all
dashes, “-”, occurring in the first component with
“.”.link:#a5381[30]
. Apply algorithm described in Section 7.7
“Unique Package Names” in [JLS] to derive a unique package name from the
potential internet domain name contained within the first component. The
internet domain name is reversed, component by component. Note that a
leading “ _www_ .” is not considered part of an internet domain name and
must be dropped.
If the first component does not contain
either one of the top-level domain names, for example, com, gov, net,
org, edu, or one of the English two-letter codes identifying countries
as specified in ISO Standard 3166, 1981, this step must be skipped.
_\{“com”, “acme”, “go”, “espeak”}_
. For each string in the list, convert each
string to be all lower case.
_\{"com”, “acme”, "go", "espeak" }_
. For each string remaining, the following
conventions are adopted from [JLS] Section 7.7, “Unique Package Names.”
. If the sting component contains a hyphen,
or any other special character not allowed in an identifier, convert it
into an underscore.
. If any of the resulting package name
components are keywords then append underscore to them.
. If any of the resulting package name
components start with a digit, or any other character that is not
allowed as an initial character of an identifier, have an underscore
prefixed to the component.
_\{"com”, “acme”, "go", "espeak" }_
. Concatenate the resultant list of strings
using _’.’_ as a separating character to produce a package name.
_Final package name: "com.acme.go.espeak"._
link:jaxb.html#a4767[See Collisions
and conflicts], specifies what to do when the above algorithm results in
an invalid Java package name.
=== [[a4816]]Conforming Java Identifier Algorithm
This section describes how to convert a legal
Java identifier which may not conform to Java naming conventions to a
Java identifier that conforms to the standard naming conventions.
link:jaxb.html#a1608[See Customized Name Mapping]“discusses when
this algorithm is applied to customization names.
Since a legal Java identifier is also a XML
name, this algorithm is the same as link:jaxb.html#a4656[See The
Name to Identifier Mapping Algorithm]” with the following exception:
constant names must not be mapped to a Java constant that conforms to
the Java naming convention for a constant.
=== Appendix
External Binding Declaration
=== [[a4821]]Example
=== Example: Consider the following schema and external binding file:
Source Schema: _A.xsd:_
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:ens="http://example.com/ns"
targetNamespace="http://example.com/ns"> +
<xs:complexType name="aType">
<xs:sequence>
<xs:element name="foo" type="xs:int"/>
</xs:sequence>
<xs:attribute name="bar" type="xs:int"/>
</xs:complexType>
<xs:element name="root" type="ens:aType"/>
</xs:schema>
External binding declarations file:
<jaxb:bindings
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="1.0">
<jaxb:bindings schemaLocation=” _A.xsd_ ”>
<jaxb:bindings
node="//xs:complexType[@name=’aType’]”>
<jaxb:class name="customNameType"/>
<jaxb:bindings
node=”.//xs:element[@name=’foo’]”> +
<jaxb:property name="customFoo"/>
</jaxb:bindings>
<jaxb:bindings
node=”./xs:attribute[@name=’bar’]”> +
<jaxb:property name="customBar"/> +
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
Conceptually, the combination of the source
schema and external binding file above are the equivalent of the
following inline annotated schema.
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema" +
xmlns:ens="http://example.com/ns" +
targetNamespace="http://example.com/ns"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" +
jaxb:version="1.0"> +
<xs:complexType name="aType"> +
_<xs:annotation> +
<xs:appinfo> +
_ _<jaxb:class name="customNameType"/> +
_ _</xs:appinfo> +
</xs:annotation> +
_ <xs:sequence> +
<xs:element name="foo" type="xs:int"> +
_<xs:annotation> +
<xs:appinfo> +
_ _<jaxb:property name="customFoo"/> +
_ _</xs:appinfo> +
</xs:annotation> +
_ </xs:element> +
</xs:sequence> +
<xs:attribute name="bar" type="xs:int"> +
_<xs:annotation> +
<xs:appinfo> +
_ _<jaxb:property name="customBar"/> +
_ _</xs:appinfo> +
</xs:annotation> +
_ </xs:attribute> +
</xs:complexType> +
<xs:element name="root" type="ens:aType"/> +
</xs:schema>
=== Transformation
The intent of this section is to describe the
transformation of external binding declarations and their target schemas
into a set of schemas annotated with JAXB binding declarations. ready
for processing by a JAXB compliant schema compiler.
This transformation must be understood to
work on XML data model level. Thus, this transformation is applicable
even for those schemas which contain semantic errors.
The transformation is applied as follows:
. Gather all the top-most _<jaxb:bindings>_
elements from all the schema documents and all the external binding
files that participate in this process. _Top-most_ _<jaxb:bindings>_ are
those _<jaxb:bindings>_ elements that are either a root element in a
document or whose parent is an _<xs:appinfo>_ element. We will refer to
these trees as “external binding forest.”
. Collect all the namespaces used in the
elements inside the external binding forest, except the taxi namespace,
_"http://java.sun.com/xml/ns/jaxb”,_ and the no namespace. Allocate an
unique prefix for each of them and declare the namespace binding at all
the root _<xs:schema>_ elements of each schema documents. +
Then add a _jaxb:extensionBindingPrefix_ attribute to each _<xs:schema>_
element with all those allocated prefixes. If an _<xs:schema>_ element
already carries this attribute, prefixes are just appended to the
existing attributes. +
+
Note: The net effect is that all “foreign” namespaces used in the
external binding forest will be automatically be considered as extension
customization declaration namespaces.
. For each _<jaxb:bindings>_ element, we
determine the “target element” that the binding declaration should be
associated with. This process proceeds in a top-down fashion as follows:
. Let _p_ be the target element of the parent
_<jaxb:bindings>_ . If it is the top most _<jaxb:bindings>_ , then let
_p_ be the < _jaxb:bindings>_ element itself.
. Identify the “target element” using
_<jaxb:bindings>_ attributes. +
(i) If the _<jaxb:bindings>_ has a _@schemaLocation_ , the value of the
attribute should be taken as an URI and be absolutized with the base URI
of the _<jaxb:bindings>_ element. Then the target element will be the
root node of the schema document identified by the absolutized URI. If
there’s no such schema document in the current input, it is an error.
Note: the root node of the schema document is not the document element.
(ii) If the _<jaxb:bindings>_ has _@node_ ,
the value of the attribute should be evaluated as an XPath 1.0
expression. The context node in this evaluation should be _p_ as we
computed in the previous step. It is an error if this evaluation results
in something other than a node set that contains exactly one element.
Then the target element will be this element.
(iii) if the _<jaxb:bindings>_ has neither
_@schemaLocation_ nor _@node_ , then the target element will be _p_ as
we computed in the previous step. Note: _<jaxb:bindings>_ elements can’t
have both _@schemaLocation_ and _@node_ at the same time.
We define the target element of a binding
declaration to be the target element of its parent _<jaxb:bindings>_
element. The only exception to this is _<jaxb:globalBindings>_ binding
declaraiton, in which case the target element will be the document
element of any one of the schema documents being compiled (such choice
is undeterministic, but the semantics of _<jaxb:globalBindings>_ is not
affected by this choice, so the end result will be the same.) It is an
error if a target element of a binding declaration doesn’t belong to the
_"http://wwww.w3.org/2001/XMLSchema"_ namespace.
. Next, for each target element of binding
declarations, if it doesn’t have any _<xs:annotation> <xs:appinfo>_ in
its children, one will be created and added as the first child of the
target. +
+
After that, we move each binding declaration under the target node of
its parent _<jaxb:bindings>_ . Consider the first _<xs:appinfo>_ child
of the target element. The binding declaration element will be moved
under this _<xs:appinfo>_ element.
=== Appendix
XML Schema
=== Abstract Schema Model
The following summarization abstract schema
component model has been extracted from [XSD Part 1] as a convenience
for those not familiar with XML Schema component model in understanding
the binding of XML Schema components to Java representation. One must
refer to [XSD Part 1] for the complete normative description for these
components.
=== [[a4867]]Simple Type Definition Schema Component
=== Simple Type Definition Schema Components
Component
Description
\{name}
Optional. An NCName as defined by
[XML-Namespaces].
\{target namespace}
Either ·absent· or a namespace name.
\{base type definition}
A simple type definition
\{facets}
A set of constraining facets.
\{fundamental facets}
A set of fundamental facets.
\{final}
A subset of \{extension, list, restriction,
union}.
\{variety}
One of \{atomic, list, union}. Depending on
the value of \{variety}, further properties are defined as follows:
atomic
_\{primitive type definition}_
A built-in primitive simple type definition.
list
_\{item type definition}_
A simple type definition.
union
_\{member type definitions}_
A non-empty sequence of simple type
definitions.
\{annotation}
Optional. An annotation.
=== [[a4899]]Enumeration Facet Schema Component
=== Enumeration Facet Schema Components
Component
Description
\{value}
The actual value of the value. (Must be in
value space of base type definition.)
\{annotation}
Optional annotation.
=== [[a4907]]Complex Type Definition Schema Component
=== Complex Type Definition Schema Components
Component
Description
\{name}
Optional. An NCName as defined by
[XML-Namespaces].
\{target namespace}
Either ·absent· or a namespace name.
\{base type definition}
Either a simple type definition or a complex
type definition.
\{scope}
Either _global_ or a complex type definition
\{derivation method}
Either extension or restriction.
\{final}
A subset of \{extension, restriction}.
\{abstract}
A boolean
\{attribute uses}
A set of attribute uses.
\{attribute wildcard}
Optional. A wildcard.
\{content type}
One of empty, a simple type definition, or a
pair consisting of a ·content model· and one of mixed, element-only.
\{prohibited substitutions}
A subset of \{extension, restriction}.
\{substitution group affiliation}
Optional. If exists, this element declaration
belongs to a substitution group and this specified element name is the
QName of the substitution head.
\{annotations}
A set of annotations.
=== [[a4937]]Element Declaration Schema Component
=== Element Declaration Schema Components
Component
Description
\{name}
An NCName as defined by [XML-Namespaces].
\{target namespace}
Either ·absent· or a namespace name
\{type definition}
Either a simple type definition or a complex
type definition.
\{scope}
Optional. Either global or a complex type
definition.
\{value constraint}
Optional. A pair consisting of a value and
one of default, fixed.
\{nillable}
A boolean.
\{identity-constraint definitions}
A set of constraint definitions.
\{substitution group affiliation}
Optional. A top-level element definition.
\{substitution group exclusions}
A subset of \{extension, restriction}.
\{disallowed substitution}
A subset of
\{substitution,extension,restriction}.
\{abstract}
A boolean.
\{annotation}
Optional. An annotation.
=== [[a4965]]Attribute Declaration Schema Component
=== Attribute Declaration Schema Components
Component
Description
\{name}
An NCName as defined by [XML-Namespaces].
\{target namespace}
If form is present and is “qualified”, or if
form is absent and the value of @attributeFormDefault on the <schema>
ancestor is “qualified”, then the schema’s \{targetNamespace}, or
·absent· if there is none, otherwise ·absent·
\{type definition}
A simple type definition.
\{scope}
Optional. Either global or a complex type
definition.
\{value constraint}
Optional. A pair consisting of a value and
one of default, fixed.
\{annotation}
Optional. An annotation.
=== Model Group Definition Schema Component
=== Model Group Definition Schema Components
Component
Description
\{name}
An NCName as defined by [XML-Namespaces].
\{target namespace}
Either ·absent· or a namespace name.
\{model group}
A model group.
\{annotation}
Optional. An annotation.
=== Identity-constraint Definition Schema Component
=== Identity-constraint Definition Schema Components
Component
Description
\{name}
An NCName as defined by [XML-Namespaces].
\{target namespace}
Either ·absent· or a namespace name.
\{identity-constraint category}
One of key, keyref or unique.
\{selector}
A restricted XPath ([XPath]) expression.
\{fields}
A non-empty list of restricted XPath
([XPath]) expressions.
\{referenced key}
Required if \{identity-constraint category}
is keyref, forbidden otherwise.
An identity-constraint definition with
\{identity-constraint category} equal to key or unique.
\{annotation}
Optional. An annotation.
=== [[a5012]]Attribute Use Schema Component
=== Attribute Use Schema Components
Component
Description
\{required}
A boolean.
\{attribute declaration}
An attribute declaration.
\{value constraint}
Optional. A pair consisting of a value and
one of default, fixed.
=== [[a5022]]Particle Schema Component
=== Particle Schema Components
Component
Description
\{min occurs}
A non-negative integer.
\{max occurs}
Either a non-negative integer or unbounded.
\{term}
One of a model group, a wildcard, or an
element declaration.
=== [[a5032]]Wildcard Schema Component
=== Wildcard Schema Components
Component
Description
\{namespace constraint}
One of any; a pair of not and a namespace
name or ·absent·; or a set whose members are either namespace names or
·absent·.
\{process contents}
One of skip, lax or strict.
\{annotation}
Optional. An annotation.
=== Model Group Schema Component
=== Model Group Components
Component
Description
\{compositor}
One of _all, choice_ or _sequence_ .
\{particles}
A list of particles.
\{annotation}
An annotation.
=== Notation Declaration Schema Component
=== Notation Declaration Components
Component
Description
\{name}
An NCName as defined by [XML-Namespaces].
\{target namespace}
Actual value of the targetNamespace
[attribute] of the parent schema element
\{system identifier}
The ·actual value· of the system [attribute],
if present, otherwise absent.
\{public identifier}
{empty}The ·actual value· of the public
[attribute]
\{annotation}
Optional. An annotation.
=== Wildcard Schema Component
=== Wildcard Components
Component
Description
\{namespace constraint}
One of _any_ ; a pair of _not_ and a
namespace name or ·absent·; or a set whose members are either namespace
names or ·absent·.
\{process contents}
One of _skip_ , _lax_ or _strict_ .
\{annotation}
Optional. An annotation.
=== Attribute Group Definition Schema Component
=== Attribute Group Definition Schema Components
Component
Description
\{name}
An NCName as defined by [XML-Namespaces].
\{target namespace}
Either ·absent· or a namespace name.
\{attribute uses}
A set of attribute uses.
\{attribute wildcard}
Optional. A wildcard. _(part of the complete
wildcard)_
\{annotation}
Optional. An annotation.
=== Appendix
Deprecated JAXB 1.0
Functionality
=== Overview
Due to significant re-architecture in JAXB
2.0 to improve efficiency, usability, schema-derived footprint and
binding framework runtime footprint, certain JAXB 1.0 operations are no
longer required to be implemented in JAXB 2.0. These deprecated
operations do still need to be supported by a JAXB 2.0 binding runtime
for JAXB 1.0 schema-derived classes.
=== [[a5094]]On-demand Validation
It is optional for a JAXB 2.0 implementation
to implement on-demand validation for JAXB 2.0 mapped classes. There is
no reasonable way to implement this functionality of JAXB 2.0 annotated
classes and leverage JAXP 1.3 validation facility. For backwards
compatibility, an implementation is required to support this
functionality for JAXB 1.0 schema-derived classes.
=== [[a5096]]Validator for JAXB 1.0 schema-derived classes
_The following text is from JAXB 1.0
Specification and applies to JAXB 1.0 schema-derived classes._
An application may wish to validate the
correctness of the Java content tree based on schema validation
constraints. This form of validation enables an application to initiate
the validation process on a Java content tree at a point in time that it
feels it should be valid. The application is notified about validation
errors and warnings detected in the Java content tree.
The _Validator_ class is responsible for
controlling the validation of a content tree of in-memory objects. The
following summarizes the available operations on the class.
public interface Validator \{ +
ValidationEventHandler _getEventHandler_ () +
void _setEventHandler_ (ValidationEventHandler)
+
boolean _validate_ (java.lang.Object subrootObject)
boolean _validateRoot_ (java.lang.Object
rootObject) +
java.lang.Object _getProperty_
(java.lang.String name) +
void _setProperty_ (java.lang.String name,
java.lang.Object value)
}
_The JAXBContext_ class provides a factory
to create a _Validator_ instance. After an application has made a series
of modifications to a Java content tree, the application validates the
content tree on-demand. As far as the application is concerned, this
validation takes place against the Java content instances and validation
constraint warnings and errors are reported to the application relative
to the Java content tree. Validation is initiated by invoking the
_validateRoot(Object)_ method on the root of the Java content tree or by
invoking _validate(Object)_ method to validate any arbitrary subtree of
the Java content tree. The only difference between these two methods is
global constraint checking (i.e. verifying ID/IDREF constraints.) The
_validateRoot(Object)_ method includes global constraint checking as
part of its operation, whereas the _validate(Object)_ method does not.
The validator governs the process of
validating the content tree, serves as a registry for identifier
references, and ensures that all local (and when appropriate, global)
structural constraints are checked before the validation process is
complete.
If a violation of a local or global
structural constraint is detected, then the application is notified of
the event with a callback passing an instance of a _ValidationEvent_ as
a parameter.
=== [[a5109]]Appendix
[[a5110]]Enhanced Binary Data
Handling
=== Overview
Optimized transmission of binary data as
attachments is described by standards such as Soap [MTOM]/Xml-binary
Optimized Packaging[XOP] and WS-I Attachment Profile 1.0 [WSIAP]. To
optimally support these standards when JAXB databinding is used within a
message passing environment, link:jaxb.html#a5149[See
jakarta.xml.bind.attachments]“specifies an API that allows for an
integrated, cooperative implementation of these standards between a
MIME-based package processor and the JAXB 2.0 unmarshal/marshal
processes. An enhanced binding of MIME content to Java representation is
specified in link:jaxb.html#a5113[See Binding MIME Binary
Data]“.
=== [[a5113]]Binding MIME Binary Data
=== Binary Data Schema Annotation
As specified in [MIME], the XML Schema
annotation attribute, _xmime:expectedContentTypes_ , lists the expected
MIME content-type(s) for element content whose type derives from the xsd
binary datatypes, _xs:base64Binary_ or x _s:hexBinary_ .
JAXB 2.0 databinding recognizes this schema
constraint to improve the binding of MIME type constrained binary data
to Java representation. The _xmime:expectedContentType_ attribute is
allowed on type definitions deriving from binary datatypes and on
element declarations with types that derive from binary datatypes. For
JAXB 2.0 binding purposes, the schema annotation,
_xmime:expectedContentTypes_ is evaluated for binding purposes for all
cases EXCEPT when the annotation is on an element declaration with a
named complex type definition. For that case, the
_xmime:expectedContentTypes_ annotation must be located directly within
the scope of the complex type definition in order to impact the binding
of the complex type definition’s simple binary content.
=== Binding Known Media Type
When _@xmime:expectedContentTypes_ schema
annotation only refers to one MIME type, it is considered a known media
type for the binary data. [MIME] does not require an _xmime:contentType_
attribute to hold the dynamic mime type for the binary data for this
case. JAXB binding can achieve an optimal binding for this case. The
default MIME type to Java datatype are in
link:jaxb.html#a5119[See Default Binding for Known Media Type].
=== [[a5119]]Default Binding for Known Media Type
[width="100%",cols="50%,50%",options="header",]
|===
|MIME Type |Java
Type
|image/gif
|java.awt.Image
|image/jpeg
|java.awt.Image
|text/xml or application/xml
|javax.xml.transform.Source
| _any other MIME types_
|javax.activation.DataHandler
|===
A JAXB program annotation element,
_@XmlMimeType_ , is generated to preserve the known media type for use
at marshal time.
=== schema with a known media type
<?xml version="1.0" ?> +
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" +
xmlns:tns="http://example.com/know-type" +
| xmlns:xmime="http://www.w3.org/2005/05/xmlmime"
targetNamespace="http://example.com/know-type">
<xs:import
namespace="http://www.w3.org/2005/05/xmlmime"
schemaLocation="http://www.w3.org/2005/05/xmlmime"/>
<xs:element name="JPEGPicture"
type="xs:base64binary" +
xmime:expectedContentTypes="image/jpeg"/> +
</xs:schema>
=== JAXB 2.0 binding of Example 9-1
import java.awt.Image; +
@XmlRegistry +
class ObjectFactory \{ +
@XmlElementDecl(...) +
@XmlMimeType("image/jpeg")
JAXBELement<Image> createJPEGPicture(Image
value); +
}
The _@XmlMimeType_ annotation provides the
MIME content type needed by JAXB 2.0 Marshaller to specify the mime type
to set _DataHandler.setContentType(String)_ .
=== [[a5140]]Schema for local element declaration annotated with known media type
<?xml version="1.0" ?> +
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" +
xmlns:tns="http://example.com/know-type" +
xmlns:xmime="http://www.w3.org/2005/05/xmlmime" +
targetNamespace="http://example.com/know-type"> +
<xs:import namespace="http://www.w3.org/2005/05/xmlmime" +
schemaLocation="http://www.w3.org/2005/05/xmlmime"/> +
<xs:complexType name="Item"> +
<xs:sequence> +
<xs:element name="JPEGPicture" +
type="xs:base64Binary" +
xmime:expectedContentTypes="image/jpeg"/> +
</xs:sequence> +
</xs:complexType> +
</xs:schema>
=== Java Binding of link:jaxb.html#a5140[See Schema for local element declaration annotated with known media type]“
import java.awt.Image; +
public class Item \{ +
@XmlMimeType("image/jpeg") +
Image getJPEGPicture(); +
void setJPEGPicture(Image value); +
}
=== Binding Preferred Media Types
If there are more than one mime type listed
in _xmime:expectedContentTypes_ or if there is one with a wildcard in
it, the annotation specifies the Preferred Media Types and recommends
that the binary data be simple content that has an attribute
_xmime:contentType_ that specifies which of the
_xmime:expectedContentTypes_ the binary data represents.
Given that the exact media type is not known
for this case, a Preferred Media Type binds to
_javax.activation.DataHandler_ . _DataHandler_ has a property
_get/setContentType_ that should be kept synchronized with the value of
the JAXB binding for the _xmime:contentType_ attribute.
=== [[a5147]]Binding WS-I Attachment Profile _ref:swaRef_
An XML element or attribute with a type
definition of _ref:swaRef_ is bound to a JAXB property with base type of
_javax.activation.DataHandler_ and annotated with _@XmlAttachmentRef_ .
=== [[a5149]]jakarta.xml.bind.attachments
The abstract classes _AttachmentUnmarshaller_
and _AttachmentMarshaller_ in package _jakarta.xml.bind.attachments_ are
intended to be implemented by a MIME-based package processor, such as
JAX-WS 2.0 implementation, and are called during JAXB unmarshal/marshal.
The JAXB unmarshal/marshal processes the root part of a MIME-based
package, delegating knowledge of the overall package and its other parts
to the _Attachment*_ class implementations.
=== AttachmentUnmarshaller
An implementation of this abstract class by a
MIME-based package processor provides access to package-level
information that is outside the scope of the JAXB unmarshal process. A
MIME-based package processor registers its processing context with a
JAXB 2.0 processor using the method
_setAttachmentUnmarshaller(AttachmentUnmarshaller)_ of
_jakarta.xml.bind.Unmarshaller_ .
Interactions between the Unmarshaller and the
abstract class are summarized below. The javadoc specifies the details.
public abstract class AttachmentUnmarshaller
\{ +
public boolean isXOPPackage(); +
public abstract DataHandler getAttachmentAsDataHandler(String cid); +
public abstract byte[] getAttachmentAsByteArray(String cid); +
}
The JAXB unmarshal process communicates with
a MIME-based package processor via an instance of AttachmentUnmarshaller
registered with the unmarshaller. link:jaxb.html#a5165[See JAXB
marshal/unmarshalling of optimized binary content.] summarizes this
processing.
* MTOM/XOP processing during unmarshal: +
When _isXOPPackage()_ returns true, the unmarshaller replaces each XOP
include element it encounters with MIME content returned by the
appropriate _getAttachment*()_ method.
* WS-I AP processing: +
Each element or attribute of type definition _ref:swaRef_ , a content-id
uri reference to binary data, is resolved by the unmarshal process by a
call to the appropriate _getAttachment*()_ method.
=== AttachmentMarshaller
An _AttachmentMarshaller_ instance is
registered with a _jakarta.xml.bind.Marshaller_ instance using the method
_Marshaller.setAttachmentMarshaller()_ .
Interactions between the Marshaller and the
abstract class is summarized below. See the javadoc for details.
public abstract class AttachmentMarshaller
\{ +
public boolean isXOPPackage(); +
public abstract String +
addMtomAttachment(DataHandler data, +
String elementNamespace, +
String elementLocalName); +
public abstract String +
addMtomAttachment(byte[] data, +
String elementNamespace, +
String elementLocalName); +
public abstract String addSwaRefAttachment(DataHandler data); +
}
When an AttachmentMarshaller instance is
registered with the Marshaller, the following processing takes place.
* MTOM/XOP processing: +
When _isXOPPackage_ () is true and a JAXB property representing binary
data is being marshalled, the method _addMtomAttachment_ (...) is called
to provide the MIME-based package processor the opportunity to decide to
optimize or inline the binary data. +
+
Note that the schema customization specified in
link:jaxb.html#a2193[See <inlineBinaryData> Declaration]“can be
used to declaratively disable XOP processing for binary data.
* WS-I AP processing: +
The _addSwaRefAttachment_ method is called when marshalling content
represented by a _ref:swaRef_ type definition. +
+
One can declaratively customize swaRef processing within a schema using
schema customization @attachmentRef of <jaxb:property>, specified in
link:jaxb.html#a1786[See Usage]“.
=== [[a5165]]JAXB marshal/unmarshalling of optimized binary content.
image:xmlb-23.png[image]
=== Appendix
Change Log
=== Changes since Proposed Final Draft
* Section 7.6.1.2, nameXmlTransform: Apply
customization [ _jaxb:nameXmlTransform]_ addition of prefix and/or
suffix after XML to Java name transformation is applied.
* Section 6.7.1-2 changed to allow generation
of element factory method for abstract element. Change was necessary to
support element substitution. The abstract element factory method is
generated so it can be annotated with JAXB program annotation that
enables element substitution, _@XmlElementDecl.substitutionHeadName_ .
* Section 7.7.3.5 fixed the example with
<class> customization. Made the corresponding change in Section 6.7.2 so
Objectfactory method creates an instance of generated class.
* Chapter 8 and appendix B:
@XmlJavaTypeAdapter on class, interface or enum type is mutually
exclusive with any other annotation.
* Chapter 8: added @XmlElement.required() for
schema generation
* Section 8.7.1.2: clarifications for no-arg
static factory method in @XmlType annotation.
* Section 8.9.13.2: Disallow use of @XmlList
on single valued property.
* Section 8.9.8.2, Table 8-30 :
@XmlAnyAttribute maps to anyAttribute with a namespace constraint with
##other.
* Section 8.9.1.2: If @XmlElement.namespace()
is different from that of the target namespace of the enclosing class,
require a global element to be generated in the namespace specified in
@XmlElement.namespace() to make the generated schema complete.
* Section 8.9.15: Allow @XmlMimeType on a
parameter.
* Section 8.9.16: Allow @XmlAttachmentRef on
a parameter.
* Chapter 8: removed constraint check that
namespace() annotation element must be a valid namespace URI from
different annotations.
* Chapter 8: Java Persistence and JAXB 2.0
alignment related changes. +
constructor requirement: public or protected no-arg constructor +
@AccessType renamed to @XmlAccessType. +
@AccessorOrder renamed to @XmlAccessOrder. +
@XmlTransient is mutually exclusive with other annotations. +
@A property or field that is transient or marked with @XmlTransient and
specified in @XmlType.propOrder is an error.
* Chapter 8: Clarifications for generics -
type variables with type bound, bounded wildcards and java.util.Map.
* Section 8.9: reworked constraints on the
properties to handle different use cases permitted by JavaBean design
pattern.
* Section 8: Take elementFormDefault into
account when determining the namespace for @XmlElement and
@XmlElementWrapper annotations.
* Section 8: Added missing mapping
constraints for @XmlElementWrapper. Also disallow use of @XmlIDREF with
@XmlElementWrapper.
* Chapter 9, “Compatibility”: clarified
schema generator and schema compiler requirements.
* Section B.2.5: Added marshalling of null
value as xsi:nil or empty element based upon @XmlElement.required and
@XmlElement.nillable annotation elements.
* Section B.5: Added new section and moved
runtime requirements on getters/setters to here.
=== Changes since Public Review
* Update link:jaxb.html#a3815[See
Compatibility]” for JAXB 2.0 technology. Additional requirements added
for Java Types to XML binding and the running of JAXB 1.0 application in
a JAXB 2.0 environment.
* Added external event callback mechanism,
_Unmarshaller.Listener_ and _Marshaller.Listener_ .
* Added new unmarshal method overloading,
unmarshal by declaredType, to _Unmarshaller_ and _Binder_ . Enables
unmarshalling a root element that corresponds with a local element
declaration in schema.
* Added link:jaxb.html#a1459[See
Modifying Schema-Derived Code]” describing use of annotation
_@javax.annotation.Generated_ to distinguish between generated and
user-modified code in schema-derived class.
* Element declaration with anonymous complex
type definition binds to _@XmlRootElement_ annotated class except for
cases in Section 6.7.3.1.
* Removed <jaxb:globalBindings
nullsInCollection>. The customization <jaxb:property
generateElementProperty=”true”> can achieve same desired result.
* Added clarification that mapping two or
more target namespaces to same java package can result in naming
collision that should be detected as an error by schema compiler.
* Added <jaxb:factoryMethod> customization to
enable the resolution of name collisions between factory methods.
* First parameter to any of the overloaded
Marshaller.marshal() methods must be a JAXB element; otherwise, method
must throw MarshalException. See updated Marshaller javadoc and
link:jaxb.html#a397[See Marshalling]” for details.
* Prepend “_”, not “Original”, to a Java
class name representing an XML Schema type definition that has been
redefined in link:jaxb.html#a1316[See Redefine]”.
* Format for class name in _jaxb.index_ file
clarified in JAXBConext.newInstance(String) method javadoc.
* Clarifications on @dom customization in
Section 7.12..
* Chapter 8: Added support for
@XmlJavaTypeAdapter at the package level.
* Chapter 8: Added new annotation
@XmlJavaTypeAdapters as a container for defining multiple
@XmlJavaTypeAdapters at the package level.
* Chapter 8: Added support for @XmlSchemaType
at the package level.
* Chapter 8: Added @XmlSchemaTypes as a
container annotation for defining multiple @XmlSchemaType annotations at
the package level.
* Chapter 8: added lists of annotations
allowed with each annotation.
* Chapter 8: Bug fixes and clarifications
related to mapping and mapping constraints.
* Chapter 8: Expanded collection types mapped
to java.util.Map and java.util.Collection.
* Appendix B. Incorporate event call backs
into unmarshalling process.
* Appendix B: Incorporate into unmarshalling
process additional unmarshal methods: Binder.unmarshal(..), unmarshal
methods that take a declaredType as a parameter - Binder.unmarshal(...,
declaredType) and Unmarshaller.unmarshal(...,declaredType).
=== Changes since Early Draft 2
* Simple type substitution support added in
Section 6.7.4.2.
* Updates to enum type binding. (Section
7.5.1, 7.5.5, 7.10, Appendix D.3)
* Optimized binary data.(Appendix H) and
schema customizations. (Section 7.13 and 7.10.5)
* Clarification for _<jaxb:globalBindings
underscoreHandling=”asCharInWord”>_ (Appendix D.2)
* Added Unmarshal and Marshal Callback Events
(Section 4.4.1,4.5.1)
* Clarification: xs:ID and xs:IDREF can not
bind to an enum type. (Section 6.2.3,7.10.5)
* Added schema customization: +
<jaxb:globalBinding localScoping=”nested”|”toplevel”> (Section 7.5.1) +
<jaxb:inlineBinaryData> (Section 7.13) +
<jaxb:property @attachmentRef/> (Section 7.8.1)
* Updated Section 6 and 7 with mapping
annotations that are generated on schema-derived JAXB
classes/properties/fields.
* Added jakarta.xml.bind.Binder class to
Section 4.8.2.
* Runtime generation of schema from JAXB
mapping annotations: JAXBContext.generateSchema().
* Chapter 8: added @XmlList: bind
property/field to simple list type
* Chapter 8: added @XmlAnyElement: bind
property/field to xs:any
* Chapter 8: added @XmlAnyAttribute - bind
property/field to xs:anyAttribute
* Chapter 8. added @XmlMixed - for mixed
content
* Chapter 8, added annotations for
attachment/MTOM support: @XmlMimeType, @XmlAttachmentRef
* Chapter 8: added @XmlAccessorOrder - to
specify default ordering.
* Chapter 8: added @XmlSchemaType mainly for
use in mapping XMLGregorianCalendar.
* Chapter 8: map java.lang.Object to
xs:anyType
* Chapter 8: added mapping of
XMLGregorianCalendar
* Chapter 8: added mapping of generics - type
variables, wildcardType
* Chapter 8: added mapping of binary data
types.
* Chapter 8: default mappings changed for
class, enum type.
* Chapter 8: default mapping of propOrder
specified.
* Chapter 8: mapping of classes - zero arg
constructor, factory method.
* Chapter 8: added Runtime schema generation
requirement.
* Chapter 8: Clarified mapping constraints
and other bug fixes.
* Added Appendix B new: Added Runtime
Processing Model to specify the marshalling/unmarshalling for dealing
with invalid XML content and schema evolution.
* Updated Appendix C to JAXB 2.0 binding
schema.
=== Changes since Early Draft
* Updated goals in Introduction.
* Update to Section 3 “Architecture”
introducing Java to Schema binding.
* section on portable annotation-driven
architecture.
* section on handling of invalid XML content
* Binding Framework
* Replaced _IXmlElement<T>_ interface with
_JAXBElement<T>_ class. (JAXBElement is used for schema to java binding)
* _JAXBIntrospector_ introduced _._
* Add flexible (by-name) unmarshal and
describe JAXB 1.0 structural unmarshalling.
* Moved deprecated on-demand validation,
accessible via jakarta.xml.bind.Validator, to Appendix H.
* XSD to Java Binding
* Bind complex type definition to value class
by default.
* Schema-derived code is annotated with JAXB
java annotations.
* Bind XSD simpleType with enum facet to J2SE
5.0 enum type. Change default for jaxb:globalBinding @typeEnumBase from
xs:NCName to xs:string.
* _ObjectFactory_ factory methods no longer
throws _JAXBException_ .
* Added customizations +
[jaxb:globalBindings] @generateValueClass, @generateElementClass,
@serializable, @optionalProperty, @nullInCollection +
[jaxb:property] @generateElementProperty
* Add binding support for redefine
* Simplified following bindings: +
- union by binding to String rather than Object. +
- Attribute Wildcard binds to portable abstraction of a
java.util.Map<QName, String>, not jakarta.xml.bind.AttributeMap. +
- bind xsd:anyType to java.lang.Object in JAXB property method
signatures and element factory method(support element/type substitution)
* Changes required for default and customized
binding in order to support flexible unmarshalling described in Section
4.4.3.
* Java to XSD Binding
* Added @XmlAccessorType for controlling
whether fields or properties are mapped by default.
* Added @XmlEnum and @XmlEnumValue for
mapping of enum types.
* Collections has been redesigned to allow
them to be used in annotation of schema derived code:
- removed @XmlCollectionItem and
@XmlCollection
- Added annotations parameters to @XmlElement
- added @XmlElementRef
- added @XmlElements and @XmlElementRefs as
containers for collections of @XmlElements or @XmlElementRefs.
- added @XmlElementWrapper for wrapping of
collections.
* Added mapping of anonymous types.
* Added mapping of nested classes to schema
* Added @XmlRootElement for annotating
classes. @XmlElement can now only be used to annotate properties/fields.
* Added @XmlElementRef for supporting schema
derived code as well as mapping of existing object model to XML
representation. javadoc for @XmlElementRef contains an example
* Added @XmlElementDecl on object factory
methods for supporting mapping of substitution groups for schema -> java
binding.
* Redesigned Adapter support for mapping of
non Java Beans.
- new package
jakarta.xml.bind.annotation.adapters for adapters.
- Added XmlAdapter base abstract class for
all adapters.
- redesigned and moved XmlJavaTypeAdapter to
the package.
* Moved default mapping from each section to
“Default Mapping” section.
* Consistent treatment of defaults
“##default”
* Removed JAX-RPC 1.1 Alignment. JAX-WS 2.0
is deferring its databinding to JAXB 2.0.
=== Changes for 2.0 +
Early Draft v0.4
* Updated link:jaxb.html#a2[See
Introduction]”.
* Added link:jaxb.html#a151[See
Requirements]”
* Added link:jaxb.html#a2236[See Java
Types To XML]” for Java Source to XML Schema mapping.
* XML Schema to schema-derived Java Binding
changes
* Element handling changes to support element
and type substitution in link:jaxb.html#a680[See Java Element
Representation Summary]”, link:jaxb.html#a1023[See Element
Declaration]” and link:jaxb.html#a630[See Element Property]”.
* Added link:jaxb.html#a1306[See
Attribute Wildcard]” binding
* Support binding all wildcard content in
link:jaxb.html#a1384[See Bind wildcard schema component]”.
* Addition/changes in
link:jaxb.html#a725[See Java Mapping for XML Schema Built-in
Types].
* XML Schema to Java Customization
* Added ability to doable databinding for an
XML Schema fragment in link:jaxb.html#a2165[See <dom>
Declaration]”.
=== Changes for 1.0 Final
* Added method
_jakarta.xml.bind.Marshaller.getNode(Object)_ which returns a DOM view of
the Java content tree. See method's javadoc for details.
=== Changes for Proposed Final
* Added link:jaxb.html#a3815[See
Compatibility].”
* Section 5.9.2, “General Content Property,”
removed value content list since it would not be tractable to support
when type and group substitution are supported by JAXB technology.
* Added the ability to associate
implementation specific property/value pairs to the unmarshal,
validation and JAXB instance creation. Changes impact Section 3.4
“Unmarshalling,” Section 3.5 “Validator” and the ObjectFactory
description in Section 4.2 “Java Package.”
* Section 6.12.10.1, “Bind a Top Level Choice
Model Group” was updated to handle Collection properties occurring
within a Choice value class.
* Section 6.12.11, “Model Group binding
algorithm” changed step 4(a) to bind to choice value class rather than
choice content property.
* link:jaxb.html#a595[See List
Property] and link:jaxb.html#a610[See isSet Property Modifier]”
updated so one can discard set value for a List property via calling
unset method.
* At end of Section 4, added an UML diagram
of the JAXB Java representation of XML content.
* Updated default binding handling in
link:jaxb.html#a996[See Model Group Definition].” Specifically,
value class, element classes and enum types are derived from the content
model of a model group definition are only bound once, not once per time
the group is referenced.
* Change link:jaxb.html#a1384[See
Bind wildcard schema component],” to bind to a JAXB property with a
basetype of _java.lang.Object,_ not _jakarta.xml.bind.Element._ Strict and
lax wildcard validation processing allows for contents constrained only
by _xsi:type_ attribute. Current APIs should allow for future support of
_xsi:type_ .
* Simplify anonymous simple type definition
binding to typesafe enum class. Replace incomplete approach to derive a
name with the requirement that the @name attribute for element
typesafeEnumClass is mandatory when associated with an anonymous simple
type definition.
* Changed link:jaxb.html#a1012[See
Deriving Class Names for Named Model Group Descendants]” to state that
all classes and interfaces generated for XML Schema component that
directly compose the content model for a model group, that these
classes/interfaces should be generated once as top-level interface/class
in a package, not in every content model that references the model
group.
* Current link:jaxb.html#a1580[See
<globalBindings> Declaration]”:
* Replaced _modelGroupAsClass_ with
_bindingStyle_ .
* Specified schema types that cannot be
listed in _typesafeEnumBase_ .
* link:jaxb.html#a1783[See <property>
Declaration]:
* Clarified the customization of model groups
with respect to _choiceContentProperty, elementBinding and
modelGroupBinding._ Dropped _choiceContentProperty_ from the
_<property>_ declaration.
* Added _<baseType>_ element and clarified
semantics.
* Added support for customization of simple
content.
* Added customization of simple types at
point of reference.
* Clarified restrictions and relationships
between different customizations.
* link:jaxb.html#a1981[See <javaType>
Declaration]”:
* Added
_jakarta.xml.bind.DatatypeConverterInterface_ interface.
* Added _jakarta.xml.bind.DatatypeConverter_
class for use by user specified parse and print methods.
* Added
_javax.xml.namespace.NamespaceContext_ class for processing of QNames.
* Clarified print and parse method
requirements.
* Added narrowing and widening conversion
requirements.
* Throughout link:jaxb.html#a1498[See
Customizing XML Schema to Java Representation Binding],” clarified the
handling of invalid customizations.
=== Changes for Public Draft 2
Many changes were prompted by inconsistencies
detected within the specification by the reference implementation
effort. Change bars indicate what has changed since Public Draft.
* Section 4.5.4, “isSetProperty Modifier,”
describes the customization required to enable its methods to he
generated.
* Section 5.7.2, “Binding of an anonymous
type definition,” clarifies the generation of value class and typesafe
enum classes from an anonymous type definition.
* Section 5.2.4, “List” Simple Type
Definition and the handling of list members within a union were added
since public draft.
* Clarification on typesafe enum global
customization “generateName” in Section 5.2.3.4, “XML Enumvalue
To Java Identifier Mapping.”
* Clarification of handling binding of
wildcard content in Section 5.9.4.
* Chapter6, “Customization,” resolved binding
declaration naming inconsistencies between specification and normative
binding schema.
* removed _enableValidation_ attribute (a
duplicate of _enableFailFastCheck)_ from < _globalBindings>_
declaration.
* Added default values for <
_globalBindings>_ declaration attributes.
* Changed _typesafeEnumBase_ to a list of
QNames. Clarified the binding to typesafe enum class.
* Clarified the usage and support for
_implClass_ attribute in _<class>_ declaration.
* Clarified the usage and support for
_enableFailFastCheck_ in the _<property>_ declaration.
* Added _<javadoc>_ to typesafe enum class,
member and property declarations.
* Mention that embedded HTML tags in
_<javadoc>_ declaration must be escaped.
* Fixed mistakes in derived Java code
throughout document.
* Added Section 7. Compatibility and updated
Appendix E.2 “Non required XML Schema Concepts” accordingly.
=== Changes for Public Draft
* link:jaxb.html#a1442[See Bind
single occurrence choice group to a choice content property],” replaced
overloading of choice content property setter method with a single
setter method with a value parameter with the common type of all members
of the choice. Since the resolution of overloaded method invocation is
performed using compile-time typing, not runtime typing, this
overloading was problematic. Same change was made to binding of union
types.
* Added details on how to construct factory
method signature for nested content and element classes.
* Section 3.3, default validation handler
does not fail on first warning, only on first error or fatal error.
* Add ID/IDREF handling in section 5.
* Updated name mapping in appendix C.
* link:jaxb.html#a572[See Indexed
Property], added getIDLenth() to indexed property.
* Removed ObjectFactory.setImplementation
method from link:jaxb.html#a482[See Java Package]. The negative
impact on implementation provided to be greater than the benefit it
provided the user.
* Introduced external binding declaration
format.
* Introduced a method to introduce extension
binding declarations.
* Added an appendix section describing JAXB
custom bindings that align JAXB binding with JAX-RPC binding from XML to
Java representation.
* Generate isID() accessor for boolean
property.
* Section 6, Customization has been
substantially rewritten.
'''''
[.footnoteNumber]# 1.# [[a5352]]In the interest of
terseness, JAXB 2.0 program annotations have been ommitted.
[.footnoteNumber]# 2.# [[a5353]]Appropriate
customization required to bind a fixed attribute to a constant value.
[.footnoteNumber]# 3.# [[a5354]]Type constraint
checking only performed if customization enables it and implementation
supports fail-fast checking
[.footnoteNumber]# 4.# [[a5355]]JAXB 1.0 deprecated
class, _jakarta.xml.bind.Validator_ , is described in
link:jaxb.html#a5096[See Validator for JAXB 1.0 schema-derived
classes]”.
[.footnoteNumber]# 5.# [[a5356]]Section 7.4.1.1
“Package Annotations” in [JLS] recommends that file-system-based
implementations have the annotated package declaration in a file called
_package-info.java_ .
[.footnoteNumber]# 6.# [[a5357]]Program annotations
@XmlRootElement and @XmlType are specified in Section 8.0.
[.footnoteNumber]# 7.# [[a5358]]Note that it is
optional for a JAXB implementation to support type constraint checks
when setting a property in this version of the specification.
[.footnoteNumber]# 8.# [[a5359]]An unmarshalling
implementation should distinguish between a value from an XML instance
document and a schema specified defaulted value when possible. A
property should only be considered to have a set value when there exists
a corresponding value in the XML content being unmarshalled.
Unfortunately, unmarshalling implementation paths do exist that can not
identify schema specified default values, this situation is considered a
one-time transformation for the property and the defaulted value will be
treated as a set value.
[.footnoteNumber]# 9.# [[a5360]]Namely, a _boolean_
field type defaults to _false_ , _integer_ field type defaults to _0_ ,
object reference field type defaults to _null_ , floating point field
type defaults to _+0.0f_ .
[.footnoteNumber]# 10.# [[a5361]]Note that it is
optional for a JAXB implementation to support type constraint checks
when setting a property in this version of the specification.
[.footnoteNumber]# 11.# [[a5362]]Note that it is
optional for a JAXB implementation to support type constraint checks
when setting a property in this version of the specification.
[.footnoteNumber]# 12.# [[a5363]]A Java application
usually does not need to distinguish between the absence of a element
from the infoset and when the element occurred with nil content. Thus,
in the interest of simplifying the generated API, methods were not
provided to distinguish between the two. Two annotation elements
@XmlElement.required and @XmlElement.nillable allow a null value to be
marshalled as an empty or nillable element.
[.footnoteNumber]# 13.# [[a5364]]The exception case is
that an element declaration with an anonymous type definition is bound
to a schema-derived value class by default as described in
link:jaxb.html#a1084[See Binding of an anonymous complex type
definition]”.
[.footnoteNumber]# 14.#
link:jaxb.html#a1369[See Bind mixed
content] describes why <ASimpleElement> element is bound to a Java
Element representation.
[.footnoteNumber]# 15.# [[a5366]]Assume a
customization that binds this local element declaration to an element
class. By default, this local declaration binds to a element instance
factory returning JAXBElement<Integer>
[.footnoteNumber]# 16.# [[a5367]]See next figure for
default binding for anonymous type definition.
[.footnoteNumber]# 17.# [[a5368]]enable type
substitution for element of xsd:anySimpleType
[.footnoteNumber]# 18.# [[a5369]]Exception cases that
do not bind to enum type: when the base type is or derives from _xs:ID_
and _xs:IDREF_ . Rationale for not binding these type definitions to an
enum type is in link:jaxb.html#a2126[See Customizable Schema
Elements]“.
[.footnoteNumber]# 19.# [[a5370]]Note for this case,
the _enumConstantValueType_ is always _java.lang.String_ .
[.footnoteNumber]# 20.#
link:jaxb.html#a1582[See Usage]”
describes the _enableFailFastCheck_ customization and
_link:jaxb.html#a256[See Validation]_ ” defines fail-fast
checking.
[.footnoteNumber]# 21.# [[a5372]]Note that
link:jaxb.html#a1084[See Binding of an anonymous complex type
definition]” defines the name and package property for anonymous type
definitions occurring within an element declaration.
[.footnoteNumber]# 22.# [[a5373]]Element substitution
extensibility does allow element substitution(s) to be defined in a
separate schema than a global element reference occurs. When schemas are
not compiled at same time, the schema to java binding declaration,
<jaxb:property generateElementProperty=”true”/> described in
link:jaxb.html#a1786[See Usage] forces the generation of an
element property for a global element reference, independent of it not
belonging to a element substitution group.
[.footnoteNumber]# 23.# [[a5374]]The desire to reduce
the overall number of schema-derived classes generated by default
influenced the decision to default to binding an element declaration to
an element instance factory. A customization described in
link:jaxb.html#a1580[See <globalBindings> Declaration] exists
that binds each element declaration to a Java element class so element
substitution checking can be enforced entirely by strongly typed method
signatures.
[.footnoteNumber]# 24.# [[a5375]]Specifying a
customization of the local element declaration A within Derived complex
type to a different property name than A would avoid the fallback
position for this case.
[.footnoteNumber]# 25.# [[a5376]]Note that primitive
Java types must be represented by their Java wrapper classes when base
type is used in the choice content property method signatures. Also, all
sequence descendants of the choice are treated as either a general
content property or are mapped to their own value class.
[.footnoteNumber]# 26.# [[a5377]]XML schema does not
associate anonymous types with a specific symbol space. However,
_nameXmlTransform_ is used since it provides a convenient way to
customize the value class to which an anonymous type is bound.
[.footnoteNumber]# 27.# [[a5378]]There is no need to
standardize the name of the generated class since
_@XmlJavaTypeAdapter.value()_ references the class.
[.footnoteNumber]# 28.# [[a5379]]There is no need to
standardize the name of the generated class since
_@XmlJavaTypeAdapter.value()_ references the class.
[.footnoteNumber]# 29.# [[a5380]]Exception case:
Underscore is not considered a punctuation mark for schema customization
_<jaxb:globalBindings underscoreHandling="asCharInWord"/>_ specified in
link:jaxb.html#a1613[See Underscore Handling]". For this
customization, underscore is considered a special letter that never
results in a word break as defined in link:jaxb.html#a4681[See
XML Word Breaks] and it is definitely not considered an uncased letter.
See example bindings in link:jaxb.html#a4755[See XML Names and
derived Java Class, Method, and Constant Names when <jaxb:globalBindings
underscoreHandling=”asCharInWord”>].
[.footnoteNumber]# 30.# [[a5381]]Sample URN
"urn:hl7-org:v3" \{"h17-org", "v3") transforms to \{"h17.org", "v3"}.