Hi Suchitha,
A message body writer can support an arbitrary number of Java types.
It all depends on how you implement the isWriteable method to accept a
Java type. However, I recommend keeping district types in different
writers as it makes the code more modular.
If you want to support a writer for writing out instances of Number
the isWriteable could be as follows:
boolean isWriteable(Class<?> type, Type genericType,
Annotation annotations[], MediaType mediaType) {
return Number.class.isAssignableFrom(type);
}
If you want to support a List<Number> isWriteable could be as follows:
boolean isWriteable(Class<?> type, Type genericType,
Annotation annotations[], MediaType mediaType) {
if (List.class.isAssignableFrom(type)) {
return verifyGenericType(genericType);
} else if (type.isArray()) {
return Number.isAssignableFrom(type.getComponentType());
} else return false;
}
private boolean verifyGenericType(Type genericType) {
if (!(genericType instanceof ParameterizedType)) return false;
final ParameterizedType pt = (ParameterizedType)genericType;
if (pt.getActualTypeArguments().length > 1) return false;
if (!(pt.getActualTypeArguments()[0] instanceof Class))
return false;
final Class listClass = (Class)pt.getActualTypeArguments()[0];
return Number.isAssignableFrom(listClass);
}
Hopefully it is apparent that supporting Number and List<Number> in
separate classes makes the implementation of the writeTo method
easier, as it means you can have implementations of
MessageBodyWriter<Number> and MessageBodyWriter<List<Number>> and do
not need to duplicate any reflection code to determine the type of the
instance in the writeTo method.
Paul.
On Aug 12, 2009, at 4:41 AM, Suchitha Koneru (sukoneru) wrote:
> Hello Jersey Users,
> When developing custom message body writers for
> basic java data types (Boolean, Int , Long etc) do we need to
> develop two instances of the message body writer , one which
> supports basic java data type and the other which supports the
> collection(List,Vector for that basic data type)
>
> For example List<Integer> and Integer can they have the same message
> body writer ?
>
> Can we use the same Message Body Writer for supporting all
> subclasses of Java.Lang.Number ?
>
> Could you please provide some pointers in this regard
>
> Thank you,
> suchitha
>