vendredi 8 avril 2016

How can I determine the unerased type of a field?

I have a generic response wrapper class:

public class Response <T> {
    T response;
}

and a class to be wrapped:

public class ServiceResponse {
    String someField;
}

When I'm deserializing an instance of Response I need to know the type of response or, by extension the actual unerased type of T.

I can use something like:

Response<ServiceResponse> response = new Response<>();
Field field = response.getClass().getDeclaredField("response");
Type type = field.getGenericType();

which then tells me that response is of type T but what I actually need is ServiceResponse

Per this SO question I tried casting as ParameterizedType but that would actually seem to apply to a field of type Response<ServiceResponse> and not the actual field within (and it fails because type can't be cast as ParameterizedType)

Is there any way to determine (at run time) the raw type of response?





Aucun commentaire:

Enregistrer un commentaire