Response object gets returned to client in response to request sent to a server. The Response class has Response.ResponseBuilder inner class that collects each properties set to its field of type Response.ResponseBuilder. Response.ResponseBuilder applies the Builder design pattern to construct Response Object.
The build() method is responsible to connect the chain of Response.ResponseBuilder objects formed in the course of build.
E.g.
Response.status(200);
status method return Response.ResponseBuilder after assigning STATUS
Response.status(200).entity( AnyObj );
entity object assigns the entity( the payload returned back) of type
Response.ResponseBuilder and gets assigned to the Response's instance varible of. After that, status also assigns the status and returns Response.ResponseBuilder instance. The builder connects them at time of build() method call.
Response.status(200).entity( obj ).build();
Finally, the build method constructs complete(with properties set forth) Response.
Now comes the question of GenericEntity object. It Represents a response entity of a generic type T.
For Instance,
GenericEntity> obj = new GenericEntity>(lst) {};
Response.status(200).entity( obj ).build();
obj is type of List as given above. entity method accepts Object type which is generic. In case, the need of specific type arises, you got to pass it as argument of GenericEntity type by which at runtime it's casted to object of Specific type.
Practical Use
Wanted for my Jersey Framework to respond JSON of Array type which was List object in my Java model back to client as part of Response object.
Therefore,
new GenericEntity> --- casts the object/payload to List type
new GenericEntity --- runtime type becomes String
Resource on Webservice Side
public Response findAllFruits(@QueryParam("frtID") String frtID ) {
List<String> lst = new ArrayList<String>();
lst.add("Banana");
lst.add("Apple");
GenericEntity<List<String>> obj = new GenericEntity<List<String>>(lst) {};
return Response.status(200).entity( obj ).build();
}
Output
Response sent back to client.
[
"Banana",
"Apple"
]
How to Read Response Entity
List<CustomType> myObj= response.readEntity(new GenericType<List<CustomType>>() {});