Class JAXBContext
- java.lang.Object
-
- javax.xml.bind.JAXBContext
-
- Direct Known Subclasses:
JAXBContext
public abstract class JAXBContext extends java.lang.ObjectTheJAXBContextclass 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" )
The JAXBContext instance is initialized from a list of colon separated Java package names. Each java package contains JAXB mapped classes, schema-derived classes and/or user annotated classes. Additionally, the java package may contain JAXB package annotations that must be processed. (see JLS, Section 7.4.1 "Named Packages").JAXBContext.newInstance( com.acme.foo.Foo.class )
The JAXBContext instance is initialized with class(es) passed as parameter(s) and classes that are statically reachable from these class(es). SeenewInstance(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.propertiesfile in each package containing schema derived classes. The property file must contain a property namedjavax.xml.bind.context.factorywhose value is the name of the class that implements thecreateContextAPIs.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 thecreateContextAPIs.In addition, the provider must call the
DatatypeConverter.setDatatypeConverterapi 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.Unmarshalling
The
Unmarshallerclass 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. TheJAXBContextobject allows the merging of global elements and type definitions across a set of schemas (listed in thecontextPath). 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 thecontextPath. 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 contextPathThe 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
ObjectFactoryclasses that exist in each of java packages contained in thecontextPath. 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 packagecom.acme.foothat contains a schema derived interface namedPurchaseOrder. 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
ObjectFactoryclasses, 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 )methodMarshalling
The
Marshallerclass 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 anunmarshaloperation. Clients can marshal a java content tree back to XML data to ajava.io.OutputStreamor ajava.io.Writer. The marshalling process can alternatively produce SAX2 event streams to a registeredContentHandleror 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
Validation has been changed significantly since JAXB 1.0. The
Validatorclass 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 onValidatorwill still work properly when deployed with the JAXB 1.0 runtime system. In JAXB 2.0, theUnmarshallerhas included convenince methods that expose the JAXP 1.3javax.xml.validationframework. Please refer to theUnmarshaller.setSchema(javax.xml.validation.Schema)API for more information.JAXB Runtime Binding Framework Compatibility
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.Discovery of JAXB implementation
To create an instance of
JAXBContext, one ofJAXBContext.newInstance(...)methods is invoked. After JAX-B implementation is discovered, call is delegated to appropriate provider's methodcreateContext(...)passing parameters from the original call.JAX-B implementation discovery happens each time
JAXBContext.newInstanceis invoked. If there is no user specific configuration provided, default JAX-B provider must be returned.Implementation discovery consists of following steps:
-
Packages/classes explicitly passed in to the
newInstance(java.lang.String)method are processed in the order they are specified, untiljaxb.propertiesfile is looked up in its package, by using the associated classloader — this isthe owner class loaderfor aClassargument, and for a package the specifiedClassLoader.If such a resource is discovered, it is
loadedas a property file, and the value of theJAXB_CONTEXT_FACTORYkey 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.
-
If the system property
JAXB_CONTEXT_FACTORYexists, 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. -
Provider of
JAXBContextFactoryis loaded using the service-provider loading facilities, defined by theServiceLoaderclass, 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.
In case ofservice configuration erroraJAXBExceptionwill be thrown. -
Look for resource
/META-INF/services/javax.xml.bind.JAXBContextusing provided class loader. Methods without class loader parameter useThread.currentThread().getContextClassLoader(). If such a resource exists, its content is assumed to be the provider factory class. This configuration method is deprecated. - Finally, if all the steps above fail, then the rest of the look up is unspecified. That said, the recommended behavior is to simply look for some hard-coded platform default JAXB implementation. This phase of the look up is so that Java SE can have its own JAXB implementation as the last resort.
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:- the class is implementation of
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. - the class is not implementation of interface above and then it is mandated to implement the following
static method signatures:
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 JAXBExceptionIn this scenario, appropriate static method is used instead of instance method. This approach is incompatible withServiceLoaderso 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).- See Also:
Marshaller,Unmarshaller, S 7.4.1 "Named Packages" in Java Language Specification- Author:
- Ryan Shoemaker, Sun Microsystems, Inc.
- Kohsuke Kawaguchi, Sun Microsystems, Inc.
- Joe Fialli, Sun Microsystems, Inc.
- Since:
- 1.6, JAXB 1.0
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.StringJAXB_CONTEXT_FACTORYThe name of the property that contains the name of the class capable of creating newJAXBContextobjects.
-
Constructor Summary
Constructors Modifier Constructor Description protectedJAXBContext()
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description Binder<org.w3c.dom.Node>createBinder()Creates aBinderfor W3C DOM.<T> Binder<T>createBinder(java.lang.Class<T> domType)Creates aBinderobject that can be used for associative/in-place unmarshalling/marshalling.JAXBIntrospectorcreateJAXBIntrospector()Creates aJAXBIntrospectorobject that can be used to introspect JAXB objects.abstract MarshallercreateMarshaller()Create aMarshallerobject that can be used to convert a java content tree into XML data.abstract UnmarshallercreateUnmarshaller()Create anUnmarshallerobject that can be used to convert XML data into a java content tree.abstract ValidatorcreateValidator()Deprecated.since JAXB2.0voidgenerateSchema(SchemaOutputResolver outputResolver)Generates the schema documents for this context.static JAXBContextnewInstance(java.lang.Class<?>... classesToBeBound)Create a new instance of aJAXBContextclass.static JAXBContextnewInstance(java.lang.Class<?>[] classesToBeBound, java.util.Map<java.lang.String,?> properties)Create a new instance of aJAXBContextclass.static JAXBContextnewInstance(java.lang.String contextPath)Create a new instance of aJAXBContextclass.static JAXBContextnewInstance(java.lang.String contextPath, java.lang.ClassLoader classLoader)Create a new instance of aJAXBContextclass.static JAXBContextnewInstance(java.lang.String contextPath, java.lang.ClassLoader classLoader, java.util.Map<java.lang.String,?> properties)Create a new instance of aJAXBContextclass.
-
-
-
Field Detail
-
JAXB_CONTEXT_FACTORY
public static final java.lang.String JAXB_CONTEXT_FACTORY
The name of the property that contains the name of the class capable of creating newJAXBContextobjects.- See Also:
- Constant Field Values
-
-
Method Detail
-
newInstance
public static JAXBContext newInstance(java.lang.String contextPath) throws JAXBException
Create a new instance of aJAXBContextclass.This is a convenience method to invoke the
newInstance(String,ClassLoader)method with the context class loader of the current thread.- Throws:
JAXBException- if an error was encountered while creating theJAXBContextsuch as- failure to locate either ObjectFactory.class or jaxb.index in the packages
- an ambiguity among global elements contained in the contextPath
- failure to locate a value for the context factory provider property
- mixing schema derived packages from different providers on the same contextPath
- packages are not open to
java.xml.bindmodule
-
newInstance
public static JAXBContext newInstance(java.lang.String contextPath, java.lang.ClassLoader classLoader) throws JAXBException
Create a new instance of aJAXBContextclass.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
jaxb.indexresource file, format described below. Note that a java package can contain both schema-derived classes and user annotated JAXB classes. Additionally, the java package may contain JAXB package annotations that must be processed. (see JLS, Section 7.4.1 "Named Packages").Every package listed on the contextPath must meet one or both of the following conditions otherwise a
JAXBExceptionwill be thrown:- it must contain ObjectFactory.class
- it must contain jaxb.index
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
newInstance(Class...), from the listed classes are also registered with JAXBContext.Constraints on class name occuring in a
jaxb.indexfile are:- Must not end with ".class".
- Class names are resolved relative to package containing
jaxb.indexfile. Only classes occuring directly in package containingjaxb.indexfile are allowed. - Fully qualified class names are not allowed. A qualified class name,relative to current package, is only allowed to specify a nested or inner class.
To maintain compatibility with JAXB 1.0 schema to java interface/implementation binding, enabled by schema customization
<jaxb:globalBindings valueClass="false">, the JAXB provider will ensure that each package on the context path has ajaxb.propertiesfile which contains a value for thejavax.xml.bind.context.factoryproperty and that all values resolve to the same provider. This requirement does not apply to JAXB annotated classes.If there are any global XML element name collisions across the various packages listed on the
contextPath, aJAXBExceptionwill be thrown.Mixing generated interface/impl bindings from multiple JAXB Providers in the same context path may result in a
JAXBExceptionbeing thrown.The steps involved in discovering the JAXB implementation is discussed in the class javadoc.
- Parameters:
contextPath- List of java package names that contain schema derived class and/or java to schema (JAXB-annotated) mapped classes. Packages incontextPaththat are in named modules must beopento at least thejava.xml.bindmodule.classLoader- This class loader will be used to locate the implementation classes.- Returns:
- a new instance of a
JAXBContext - Throws:
JAXBException- if an error was encountered while creating theJAXBContextsuch as- failure to locate either ObjectFactory.class or jaxb.index in the packages
- an ambiguity among global elements contained in the contextPath
- failure to locate a value for the context factory provider property
- mixing schema derived packages from different providers on the same contextPath
- packages are not open to
java.xml.bindmodule
-
newInstance
public static JAXBContext newInstance(java.lang.String contextPath, java.lang.ClassLoader classLoader, java.util.Map<java.lang.String,?> properties) throws JAXBException
Create a new instance of aJAXBContextclass.This is mostly the same as
newInstance(String, ClassLoader), but this version allows you to pass in provider-specific properties to configure the instantiation ofJAXBContext.The interpretation of properties is up to implementations. Implementations must throw
JAXBExceptionif it finds properties that it doesn't understand.- Parameters:
contextPath- List of java package names that contain schema derived class and/or java to schema (JAXB-annotated) mapped classes. Packages incontextPaththat are in named modules must beopento at least thejava.xml.bindmodule.classLoader- This class loader will be used to locate the implementation classes.properties- provider-specific properties. Can be null, which means the same thing as passing in an empty map.- Returns:
- a new instance of a
JAXBContext - Throws:
JAXBException- if an error was encountered while creating theJAXBContextsuch as- failure to locate either ObjectFactory.class or jaxb.index in the packages
- an ambiguity among global elements contained in the contextPath
- failure to locate a value for the context factory provider property
- mixing schema derived packages from different providers on the same contextPath
- packages are not open to
java.xml.bindmodule
- Since:
- 1.6, JAXB 2.0
-
newInstance
public static JAXBContext newInstance(java.lang.Class<?>... classesToBeBound) throws JAXBException
Create a new instance of aJAXBContextclass.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
@XmlTransientreferenced classes are not registered with JAXBContext. For example, in the following Java code, if you donewInstance(Foo.class), the newly createdJAXBContextwill recognize bothFooandBar, but notZotorFooBar: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.
- Parameters:
classesToBeBound- List of java classes to be recognized by the newJAXBContext. Classes inclassesToBeBoundthat are in named modules must be in a package that isopento at least thejava.xml.bindmodule. Can be empty, in which case aJAXBContextthat only knows about spec-defined classes will be returned.- Returns:
- A new instance of a
JAXBContext. - Throws:
JAXBException- if an error was encountered while creating theJAXBContext, such as (but not limited to):- No JAXB implementation was discovered
- Classes use JAXB annotations incorrectly
- Classes have colliding annotations (i.e., two classes with the same type name)
- The JAXB implementation was unable to locate provider-specific out-of-band information (such as additional files generated at the development time.)
classesToBeBoundare not open tojava.xml.bindmodule
java.lang.IllegalArgumentException- if the parameter containsnull(i.e.,newInstance(null);)- Since:
- 1.6, JAXB 2.0
-
newInstance
public static JAXBContext newInstance(java.lang.Class<?>[] classesToBeBound, java.util.Map<java.lang.String,?> properties) throws JAXBException
Create a new instance of aJAXBContextclass.An overloading of
newInstance(Class...)to configure 'properties' for this instantiation ofJAXBContext.The interpretation of properties is up to implementations. Implementations must throw
JAXBExceptionif it finds properties that it doesn't understand.- Parameters:
classesToBeBound- List of java classes to be recognized by the newJAXBContext. Classes inclassesToBeBoundthat are in named modules must be in a package that isopento at least thejava.xml.bindmodule. Can be empty, in which case aJAXBContextthat only knows about spec-defined classes will be returned.properties- provider-specific properties. Can be null, which means the same thing as passing in an empty map.- Returns:
- A new instance of a
JAXBContext. - Throws:
JAXBException- if an error was encountered while creating theJAXBContext, such as (but not limited to):- No JAXB implementation was discovered
- Classes use JAXB annotations incorrectly
- Classes have colliding annotations (i.e., two classes with the same type name)
- The JAXB implementation was unable to locate provider-specific out-of-band information (such as additional files generated at the development time.)
classesToBeBoundare not open tojava.xml.bindmodule
java.lang.IllegalArgumentException- if the parameter containsnull(i.e.,newInstance(null,someMap);)- Since:
- 1.6, JAXB 2.0
-
createUnmarshaller
public abstract Unmarshaller createUnmarshaller() throws JAXBException
Create anUnmarshallerobject that can be used to convert XML data into a java content tree.- Returns:
- an
Unmarshallerobject - Throws:
JAXBException- if an error was encountered while creating theUnmarshallerobject
-
createMarshaller
public abstract Marshaller createMarshaller() throws JAXBException
Create aMarshallerobject that can be used to convert a java content tree into XML data.- Returns:
- a
Marshallerobject - Throws:
JAXBException- if an error was encountered while creating theMarshallerobject
-
createValidator
@Deprecated public abstract Validator createValidator() throws JAXBException
Deprecated.since JAXB2.0Validatorhas been made optional and deprecated in JAXB 2.0. Please refer to the javadoc forValidatorfor more detail.Create a
Validatorobject that can be used to validate a java content tree against its source schema.- Returns:
- a
Validatorobject - Throws:
JAXBException- if an error was encountered while creating theValidatorobject
-
createBinder
public <T> Binder<T> createBinder(java.lang.Class<T> domType)
Creates aBinderobject that can be used for associative/in-place unmarshalling/marshalling.- Parameters:
domType- select the DOM API to use by passing in its DOM Node class.- Returns:
- always a new valid
Binderobject. - Throws:
java.lang.UnsupportedOperationException- if DOM API corresponding todomTypeis not supported by the implementation.- Since:
- 1.6, JAXB 2.0
-
createBinder
public Binder<org.w3c.dom.Node> createBinder()
Creates aBinderfor W3C DOM.- Returns:
- always a new valid
Binderobject. - Since:
- 1.6, JAXB 2.0
-
createJAXBIntrospector
public JAXBIntrospector createJAXBIntrospector()
Creates aJAXBIntrospectorobject that can be used to introspect JAXB objects.- Returns:
- always return a non-null valid
JAXBIntrospectorobject. - Throws:
java.lang.UnsupportedOperationException- Calling this method on JAXB 1.0 implementations will throw an UnsupportedOperationException.- Since:
- 1.6, JAXB 2.0
-
generateSchema
public void generateSchema(SchemaOutputResolver outputResolver) throws java.io.IOException
Generates the schema documents for this context.- Parameters:
outputResolver- this object controls the output to which schemas will be sent.- Throws:
java.io.IOException- ifSchemaOutputResolverthrows anIOException.java.lang.UnsupportedOperationException- Calling this method on JAXB 1.0 implementations will throw an UnsupportedOperationException.- Since:
- 1.6, JAXB 2.0
-
-