Java Reference
In-Depth Information
shaller.isWriteable()
implementation. This parameter would be useful, for example, if
we wanted to know the type parameter of a
java.util.List
generic type.
The third parameter is an array of
java.lang.annotation.Annotation
objects. These an-
notations are applied to the JAX-RS resource method we are marshalling the response for.
Some
MessageBodyWriters
may be triggered by JAX-RS resource method annotations
rather than class annotations. In our
JAXBMarshaller
class, we do not use this parameter in
our
isWriteable()
implementation.
The fourth parameter is the media type that our JAX-RS resource method wants to produce.
Let's examine the rest of our
JAXBMarshaller
implementation:
public
public
long
long
getSize
(
Object obj
,
Class
<?>
type
,
Type genericType
,
Annotation
[]
annotations
,
MediaType mediaType
)
{
return
return
−
1
;
}
The
getSize()
method is responsible for determining the
Content-Length
of the response.
If you cannot easily determine the length, just return -1. The underlying HTTP layer (i.e., a
servlet container) will handle populating the
Content-Length
in this scenario or use the
chunked transfer encoding.
The first parameter of
getSize()
is the actual object we are outputting. The rest of the para-
meters serve the same purpose as the parameters for the
isWriteable()
method.
Finally, let's look at how we actually write the JAXB object as XML:
public
public
void
void
writeTo
(
Object target
,
Class
<?>
type
,
Type genericType
,
Annotation
[]
annotations
,
MediaType mediaType
,
MultivaluedMap
<
String
,
Object
>
httpHeaders
,
OutputStream outputStream
)
throws
throws
IOException
{
try
try
{
JAXBContext ctx
=
JAXBContext
.
newInstance
(
type
);
ctx
.
createMarshaller
().
marshal
(
target
,
outputStream
);
}
catch
catch
(
JAXBException ex
) {
throw
throw new
new
RuntimeException
(
ex
);
}
}