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, marshal and validate.
A client application normally obtains new instances of this class using one of these two styles for newInstance methods, although there are other specialized forms of the method available:
JAXBContext.newInstance( "com.acme.foo:com.acme.bar" ) JAXBContext.newInstance( com.acme.foo.Foo.class ) newInstance(Class...) for details.
The following JAXB 1.0 requirement is only required for schema to
java interface/implementation binding. It does not apply to JAXB annotated
classes. JAXB Providers must generate a jaxb.properties file in
each package containing schema derived classes. The property file must
contain a property named javax.xml.bind.context.factory whose
value is the name of the class that implements the createContext
APIs.
The class supplied by the provider does not have to be assignable to
javax.xml.bind.JAXBContext, it simply has to provide a class that
implements the createContext APIs.
In addition, the provider must call the
DatatypeConverter.setDatatypeConverter api prior to any client
invocations of the marshal and unmarshal methods. This is necessary to
configure the datatype converter that will be used during these operations.
The Unmarshaller class provides the client application the ability
to convert XML data into a tree of Java content objects.
The unmarshal method allows for
any global XML element declared in the schema to be unmarshalled as
the root of an instance document.
Additionally, the unmarshal method allows for an unrecognized root element that
has an xsi:type attribute's value that references a type definition declared in
the schema to be unmarshalled as the root of an instance document.
The JAXBContext object
allows the merging of global elements and type definitions across a set of schemas (listed
in the contextPath). Since each schema in the schema set can belong
to distinct namespaces, the unification of schemas to an unmarshalling
context must be namespace independent. This means that a client
application is able to unmarshal XML documents that are instances of
any of the schemas listed in the contextPath. For example:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo:com.acme.bar" );
Unmarshaller u = jc.createUnmarshaller();
FooObject fooObj = (FooObject)u.unmarshal( new File( "foo.xml" ) ); // ok
BarObject barObj = (BarObject)u.unmarshal( new File( "bar.xml" ) ); // ok
BazObject bazObj = (BazObject)u.unmarshal( new File( "baz.xml" ) ); // error, "com.acme.baz" not in contextPath
The client application may also generate Java content trees explicitly rather
than unmarshalling existing XML data. For all JAXB-annotated value classes,
an application can create content using constructors.
For schema-derived interface/implementation classes and for the
creation of elements that are not bound to a JAXB-annotated
class, an application needs to have access and knowledge about each of
the schema derived ObjectFactory classes that exist in each of
java packages contained in the contextPath. For each schema
derived java class, there is a static factory method that produces objects
of that type. For example,
assume that after compiling a schema, you have a package com.acme.foo
that contains a schema derived interface named PurchaseOrder. In
order to create objects of that type, the client application would use the
factory method like this:
com.acme.foo.PurchaseOrder po =
com.acme.foo.ObjectFactory.createPurchaseOrder();
Once the client application has an instance of the the schema derived object, it can use the mutator methods to set content on it.
For more information on the generated ObjectFactory classes, see
Section 4.2 Java Package of the specification.
The provider must generate a class in each
package that contains all of the necessary object factory methods for that
package named ObjectFactory as well as the static
newInstance( javaContentInterface ) method
The Marshaller class provides the client application the ability
to convert a Java content tree back into XML data. There is no difference
between marshalling a content tree that is created manually using the factory
methods and marshalling a content tree that is the result an unmarshal
operation. Clients can marshal a java content tree back to XML data
to a java.io.OutputStream or a java.io.Writer. The
marshalling process can alternatively produce SAX2 event streams to a
registered ContentHandler or produce a DOM Node object.
Client applications have control over the output encoding as well as
whether or not to marshal the XML data as a complete document or
as a fragment.
Here is a simple example that unmarshals an XML document and then marshals it back out:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
// unmarshal from foo.xml
Unmarshaller u = jc.createUnmarshaller();
FooObject fooObj = (FooObject)u.unmarshal( new File( "foo.xml" ) );
// marshal to System.out
Marshaller m = jc.createMarshaller();
m.marshal( fooObj, System.out );
Validation has been changed significantly since JAXB 1.0. The Validator
class has been deprecated and made optional. This means that you are advised
not to use this class and, in fact, it may not even be available depending on
your JAXB provider. JAXB 1.0 client applications that rely on Validator
will still work properly when deployed with the JAXB 1.0 runtime system.
In JAXB 2.0, the Unmarshaller has included convenince methods that expose
the JAXP 1.3 javax.xml.validation framework. Please refer to the
Unmarshaller#setSchema(javax.xml.validation.Schema) API for more
information.
The following JAXB 1.0 restriction only applies to binding schema to
interfaces/implementation classes.
Since this binding does not require a common runtime system, a JAXB
client application must not attempt to mix runtime objects (JAXBContext,
Marshaller, etc. ) from different providers. This does not
mean that the client application isn't portable, it simply means that a
client has to use a runtime system provided by the same provider that was
used to compile the schema.
To create an instance of JAXBContext, one of JAXBContext.newInstance(...) methods is invoked. After
JAX-B implementation is discovered, call is delegated to appropriate provider's method createContext(...)
passing parameters from the original call.
JAX-B implementation discovery happens each time JAXBContext.newInstance is invoked. If there is no user
specific configuration provided, default JAX-B provider must be returned.
Implementation discovery consists of following steps:
newInstance method are processed in the order they are
specified, until jaxb.properties file is looked up in its package, by using the associated classloader —
this is the owner class loader for a Class argument, and for a package
the specified ClassLoader.
If such a resource is discovered, it is loaded as a property file, and
the value of the JAXB_CONTEXT_FACTORY key will be assumed to be the provider factory class. If no value
found, "javax.xml.bind.context.factory" is used as a key for backwards compatibility reasons. This class is
then loaded by the associated class loader discussed above.
This phase of the look up allows some packages to force the use of a certain JAXB implementation. (For example, perhaps the schema compiler has generated some vendor extension in the code.)
This configuration method is deprecated.
JAXB_CONTEXT_FACTORY exists, then its value is assumed to be the provider
factory class. If no such property exists, properties "javax.xml.bind.context.factory" and
"javax.xml.bind.JAXBContext" are checked too (in this order), for backwards compatibility reasons. This phase
of the look up enables per-JVM override of the JAXB implementation.
javax.xml.bind.JAXBContextFactory is loaded using the service-provider loading
facilities, defined by the java.util.ServiceLoader class, to attempt
to locate and load an implementation of the service using the default loading mechanism: the service-provider loading facility
will use the current thread's context class loader
to attempt to load the context factory. If the context class loader is null, the
system class loader will be used.
service
configuration error a javax.xml.bind.JAXBException will be thrown.
/META-INF/services/javax.xml.bind.JAXBContext using provided class loader.
Methods without class loader parameter use Thread.currentThread().getContextClassLoader().
If such a resource exists, its content is assumed to be the provider factory class.
This configuration method is deprecated.
Once the provider factory class is discovered, context creation is delegated to one of its
createContext(...) methods.
For backward compatibility reasons, there are two ways how to implement provider factory class:
javax.xml.bind.JAXBContextFactory. It must also implement no-arg
constructor. If discovered in other step then 3, new instance using no-arg constructor is created first.
After that, appropriate instance method is invoked on this instance.
public static JAXBContext createContext(
String contextPath,
ClassLoader classLoader,
Map<String,Object> properties ) throws JAXBException
public static JAXBContext createContext(
Class[] classes,
Map<String,Object> properties ) throws JAXBException
In this scenario, appropriate static method is used instead of instance method. This approach is incompatible
with java.util.ServiceLoader so it can't be used with step 3.
There is no difference in behavior of given method createContext(...) regardless of whether it uses approach
1 (JAXBContextFactory) or 2 (no interface, static methods).
API Note
Service discovery method using resource /META-INF/services/javax.xml.bind.JAXBContext (described in step 4)
is supported only to allow backwards compatibility, it is strongly recommended to migrate to standard
java.util.ServiceLoader mechanism (described in step 3). The difference here is the resource name, which
doesn't match service's type name.
Also using providers implementing interface JAXBContextFactory is preferred over using ones defining
static methods, same as JAXBContext#JAXB_CONTEXT_FACTORY property is preferred over property
"javax.xml.bind.context.factory"
Implementation Note
Within the last step, if Glassfish AS environment detected, its specific service loader is used to find factory class.
Marshaller, Unmarshaller, S 7.4.1 "Named Packages" in Java Language Specification
| Modifier and Type | Field and Description |
|---|---|
| public static final String | JAXB_CONTEXT_FACTORY
The name of the property that contains the name of the class capable
of creating new |
| Access | Constructor and Description |
|---|---|
| protected |
| Modifier and Type | Method and Description |
|---|---|
| public <T> Binder | Returns: always a new validBinder object.select the DOM API to use by passing in its DOM Node class. domType)Creates a |
| public Binder | |
| public JAXBIntrospector | Returns: always return a non-null validJAXBIntrospector object.Creates a |
| public abstract Marshaller | Returns: aMarshaller objectCreate a |
| public abstract Unmarshaller | Returns: anUnmarshaller objectCreate an |
| public abstract Validator | Returns: aValidator object
Deprecated
since JAXB2.0
Validator has been made optional and deprecated in JAXB 2.0.
|
| public void | generateSchema(SchemaOutputResolver
this object controls the output to which schemas
will be sent. outputResolver)Generates the schema documents for this context. |
| private static ClassLoader | |
| public static JAXBContext | |
| public static JAXBContext | Returns: a new instance of aJAXBContextList of java package names that contain schema
derived class and/or java to schema (JAXB-annotated)
mapped classes.
Packages in contextPath, ClassLoader contextPath that are in named modules must be
open to at least the java.xml.bind module.This class loader will be used to locate the implementation
classes. classLoader)Create a new instance of a |
| public static JAXBContext | Returns: a new instance of aJAXBContextList of java package names that contain schema
derived class and/or java to schema (JAXB-annotated)
mapped classes.
Packages in contextPath, ClassLoader contextPath that are in named modules must be
open to at least the java.xml.bind module.This class loader will be used to locate the implementation classes. classLoader, Map<String, ?> provider-specific properties. Can be null, which means the same thing as passing
in an empty map. properties)Create a new instance of a |
| public static JAXBContext | Returns: A new instance of aJAXBContext.List of java classes to be recognized by the new classesToBeBound)JAXBContext.
Classes in classesToBeBound that are in named modules must be in a package
that is open to at least the java.xml.bind module.
Can be empty, in which case a JAXBContext that only knows about
spec-defined classes will be returned.Create a new instance of a |
| public static JAXBContext | Returns: A new instance of aJAXBContext.List of java classes to be recognized by the new classesToBeBound, Map<String, ?> JAXBContext.
Classes in classesToBeBound that are in named modules must be in a package
that is open to at least the java.xml.bind module.
Can be empty, in which case a JAXBContext that only knows about
spec-defined classes will be returned.provider-specific properties. Can be null, which means the same thing as passing
in an empty map. properties)Create a new instance of a |
| JAXB_CONTEXT_FACTORY | back to summary |
|---|---|
| public static final String JAXB_CONTEXT_FACTORY The name of the property that contains the name of the class capable
of creating new | |
| JAXBContext | back to summary |
|---|---|
| protected JAXBContext() | |
| createBinder | back to summary |
|---|---|
| public <T> Binder Creates a
| |
| createBinder | back to summary |
|---|---|
| public Binder Creates a | |
| createJAXBIntrospector | back to summary |
|---|---|
| public JAXBIntrospector createJAXBIntrospector() Creates a
| |
| createMarshaller | back to summary |
|---|---|
| public abstract Marshaller createMarshaller() throws JAXBException Create a
| |
| createUnmarshaller | back to summary |
|---|---|
| public abstract Unmarshaller createUnmarshaller() throws JAXBException Create an
| |
| createValidator | back to summary |
|---|---|
| public abstract Validator createValidator() throws JAXBException
Deprecated since JAXB2.0
Create a
| |
| generateSchema | back to summary |
|---|---|
| public void generateSchema(SchemaOutputResolver outputResolver) throws IOException Generates the schema documents for this context.
| |
| getContextClassLoader | back to summary |
|---|---|
| private static ClassLoader getContextClassLoader() | |
| newInstance | back to summary |
|---|---|
| public static JAXBContext newInstance(String contextPath) throws JAXBException Create a new instance of a
This is a convenience method to invoke the
| |
| newInstance | back to summary |
|---|---|
| public static JAXBContext newInstance(String contextPath, ClassLoader classLoader) throws JAXBException Create a new instance of a
The client application must supply a context path which is a list of
colon (':', \u003A) separated java package names that contain
schema-derived classes and/or fully qualified JAXB-annotated classes.
Schema-derived
code is registered with the JAXBContext by the
ObjectFactory.class generated per package.
Alternatively than being listed in the context path, programmer
annotated JAXB mapped classes can be listed in a
Every package listed on the contextPath must meet one or both of the
following conditions otherwise a
Format for jaxb.index
The file contains a newline-separated list of class names.
Space and tab characters, as well as blank
lines, are ignored. The comment character
is '#' (0x23); on each line all characters following the first comment
character are ignored. The file must be encoded in UTF-8. Classes that
are reachable, as defined in
Constraints on class name occuring in a
To maintain compatibility with JAXB 1.0 schema to java
interface/implementation binding, enabled by schema customization
If there are any global XML element name collisions across the various
packages listed on the
Mixing generated interface/impl bindings from multiple JAXB Providers
in the same context path may result in a The steps involved in discovering the JAXB implementation is discussed in the class javadoc.
| |
| newInstance | back to summary |
|---|---|
| public static JAXBContext newInstance(String contextPath, ClassLoader classLoader, Map<String, ?> properties) throws JAXBException Create a new instance of a
This is mostly the same as
The interpretation of properties is up to implementations. Implementations must
throw
| |
| newInstance | back to summary |
|---|---|
| public static JAXBContext newInstance(Class<?>... classesToBeBound) throws JAXBException Create a new instance of a
The client application must supply a list of classes that the new
context object needs to recognize.
Not only the new context will recognize all the classes specified,
but it will also recognize any classes that are directly/indirectly
referenced statically from the specified classes. Subclasses of
referenced classes nor
class Foo {
@XmlTransient FooBar c;
Bar b;
}
class Bar { int x; }
class Zot extends Bar { int y; }
class FooBar { }
Therefore, a typical client application only needs to specify the
top-level classes, but it needs to be careful.
Note that for each java package registered with JAXBContext, when the optional package annotations exist, they must be processed. (see JLS, Section 7.4.1 "Named Packages"). The steps involved in discovering the JAXB implementation is discussed in the class javadoc.
| |
| newInstance | back to summary |
|---|---|
| public static JAXBContext newInstance(Class<?>[] classesToBeBound, Map<String, ?> properties) throws JAXBException Create a new instance of a
An overloading of
The interpretation of properties is up to implementations. Implementations must
throw
| |