public class GenericEntity<T>
extends java.lang.Object
T
.
Normally type erasure removes generic type information such that a
Response
instance that contains, e.g., an entity of type
List<String>
appears to contain a raw List<?>
at runtime.
When the generic type is required to select a suitable
MessageBodyWriter
, this class may be used to wrap the entity and
capture its generic type.
There are two ways to create an instance:
Response
containing an entity of type List<String>
whose
generic type will be available at runtime for selection of a suitable
MessageBodyWriter
:
List<String> list = new ArrayList<String>(); GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) {}; Response response = Response.ok(entity).build();
where list
is the instance of List<String>
that will form the response body and entity is an instance of an anonymous
subclass of GenericEntity
.
Method method = ...; GenericEntity<Object> entity = new GenericEntity<Object>( method.invoke(...), method.getGenericReturnType()); Response response = Response.ok(entity).build();
The above obtains the generic type from the return type of the method, the raw type is the class of entity.
Modifier | Constructor and Description |
---|---|
protected |
GenericEntity(T entity)
Constructs a new generic entity.
|
|
GenericEntity(T entity,
java.lang.reflect.Type genericType)
Create a new instance of GenericEntity, supplying the generic type
information.
|
Modifier and Type | Method and Description |
---|---|
T |
getEntity()
Get the enclosed entity
|
java.lang.Class<?> |
getRawType()
Gets the raw type of the enclosed entity.
|
java.lang.reflect.Type |
getType()
Gets underlying
Type instance. |
protected GenericEntity(T entity)
entity
- the entity instance, must not be nulljava.lang.IllegalArgumentException
- if entity is nullpublic GenericEntity(T entity, java.lang.reflect.Type genericType)
entity
is an instance of
ArrayList<String>
then genericType
could
be the same or a superclass of ArrayList
with the same generic
type like List<String>
.entity
- the entity instance, must not be nullgenericType
- the generic type, must not be nulljava.lang.IllegalArgumentException
- if the entity is not assignable to
a variable of the supplied generic type or if entity or genericType
is null.public final java.lang.Class<?> getRawType()
ArrayList
not List
.public final java.lang.reflect.Type getType()
Type
instance. Note that this is derived from the
type parameter, not the enclosed instance. I.e. in the example
in the introduction, the type is List<String>
not
ArrayList<String>
.public final T getEntity()
Copyright © 2016 Oracle Corporation. All Rights Reserved.