Java Reference
In-Depth Information
boolean
boolean
pretty
=
false
false
;
for
for
(
Annotation ann
:
annotations
) {
iif
(
ann
.
annotationType
().
equals
(
Pretty
.
class
)) {
pretty
=
true
true
;
break
break
;
}
}
iif
(
pretty
) {
marshaller
.
setProperty
(
Marshaller
.
JAXB_FORMATTED_OUTPUT
,
true
true
);
}
m
.
marshal
(
target
,
outputStream
);
}
catch
catch
(
JAXBException ex
) {
throw
throw new
new
RuntimeException
(
ex
);
}
}
Here, we iterate over the
annotations
parameter to see if any of them are the
@Pretty
an-
notation. If
@Pretty
has been set, we set the
JAXB_FORMATTED_OUTPUT
property on the
Mar-
shaller
so that it will format the XML with line breaks and indentation strings.
Pluggable JAXBContexts using ContextResolvers
Earlier in this chapter, we saw how you could plug in your own
JAXBContext
using the
Con-
textResolver
interface. Let's look at how we can add this functionality to our
JAXBMar-
shaller
class.
First, we need a way to locate a
ContextResolver
that can provide a custom
JAXBContext
.
We do this through the
javax.ws.rs.ext.Providers
interface:
public
public interface
interface
Providers
Providers
{
<
T
>
ContextResolver
<
T
>
getContextResolver
(
Class
<
T
>
contextType
,
MediaType mediaType
);
<
T
>
MessageBodyReader
<
T
>
getMessageBodyReader
(
Class
<
T
>
type
,
Type genericType
,
Annotation annotations
[],
MediaType mediaType
);
<
T
>
MessageBodyWriter
<
T
>
getMessageBodyWriter
(
Class
<
T
>
type
,
Type genericType
,
Annotation annotations
[],
MediaType mediaType
);