45.4. Returning entities with generic type information

Overview

There are occasions where the application needs more control over the MIME type of the returned object or the entity provider used to serialize the response. The JAX-RS javax.ws.rs.core.GenericEntity<T> class provides finer control over the serializing of entities by providing a mechanism for specifying the generic type of the object representing the entity.

Using a GenericEntity<T> object

One of the criteria used for selecting the entity provider that serializes a response is the generic type of the object. The generic type of an object represents the Java type of the object. When a common Java type or a JAXB object is returned, the runtime can use Java reflection to determine the generic type. However, when a JAX-RS Response object is returned, the runtime cannot determine the generic type of the wrapped entity and the actual Java class of the object is used as the Java type.
To ensure that the entity provider is provided with correct generic type information, the entity can be wrapped in a GenericEntity<T> object before being added to the Response object being returned.
Resource methods can also directly return a GenericEntity<T> object. In practice, this approach is rarely used. The generic type information determined by reflection of an unwrapped entity and the generic type information stored for an entity wrapped in a GenericEntity<T> object are typically the same.

Creating a GenericEntity<T> object

There are two ways to create a GenericEntity<T> object:
  1. Create a subclass of the GenericEntity<T> class using the entity being wrapped. Example 45.11, “Creating a GenericEntity<T> object using a subclass” shows how to create a GenericEntity<T> object containing an entity of type List<String> whose generic type will be available at runtime.

    Example 45.11. Creating a GenericEntity<T> object using a subclass

    import javax.ws.rs.core.GenericEntity;
    
    List<String> list = new ArrayList<String>();
    ...
    GenericEntity<List<String>> entity = 
      new GenericEntity<List<String>>(list) {};
    Response response = Response.ok(entity).build();
    Tip
    The subclass used to create a GenericEntity<T> object is typically anonymous.
  2. Create an instance directly by supplying the generic type information with the entity. Example 45.12, “Directly instantiating a GenericEntity<T> object” shows how to create a response containing an entity of type AtomicInteger.

    Example 45.12. Directly instantiating a GenericEntity<T> object

    import javax.ws.rs.core.GenericEntity;
    
    AtomicInteger result = new AtomicInteger(12);
    GenericEntity<AtomicInteger> entity = 
      new GenericEntity<AtomicInteger>(result, 
                                          result.getClass().getGenericSuperclass());
    Response response = Response.ok(entity).build();