You're viewing all posts tagged with jersey

getting a generic List from a JAXB-RS Web service

If you consume a JAXB-RS web service using Jersey, you might encounter an issue when attempting to construct a generic List returned by the service.  To get a simple object, you would simply call this code:

Client client = Client.create();
Foo foo = client.resource(url).type(mimeType).get(Foo.class);

But because of type erasure, this isn’t as straightforward for returning a generic collection. As with most APIs that require type-information at runtime for generics, you have to pass in a type token. With Jersey, you can do that by passing in a concrete instance of com.sun.jersey.api.client.GenericType.

Client client = Client.create();
List listOfFoos = client.resource(url).type(mimeType).get(new GenericType<List<Foo>>() {});

This works because when you create a construct a subclass for a generic type, the class can, via reflection, obtain its own parameterized type.

Type superclass = getClass().getGenericSuperclass();
Type myTypeArguments = ((ParameterizedType)superclass).getActualTypeArguments()[0];

This is why GenericType is abstract and you are forced to instantiate a subclass with the type information you want Jersey to know about.

Not exactly an ideal solution (reified generics would be better), but it gets the job done.