How to determine an uneven field type?

I have a generic response wrapper class:

public class Response <T> { T response; } 

and unrelated classes that need to be wrapped:

 public class ServiceResponse { String someField; } 

When I make a service request, I get a JSON response that looks something like this:

 { "code":200, "response":{"someField":"some text"} } 

Now all my service responses have the same outer wrapper, i.e. they all have:

 { "code":200, "timestamp":"....", "response":... } 

But the actual format / type of the response field is different for each service request. When I deserialize the response, I need to know the type of the response field, so I can create an appropriate instance, if deserialization was done in response , I could use:

 response = new T(jsonParser); 

However, I do all this from a library that is controlled by reflection, so I usually deserialize the whole tree with code like:

 wrapper = deserializer.parseObject(Response<ServiceResponse>.class) 

but at this moment my parseObject method cannot correctly determine type 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 I really need ServiceResponse

Per this SO question. I tried casting as ParameterizedType , but actually it applies to a field of type Response<ServiceResponse> and not to the actual field inside (and it fails because type cannot be distinguished as ParameterizedType )

Is it possible to determine (at run time) the raw type response ?

In the end, I may need to create an annotation that will describe in more detail how to deserialize the field, perhaps providing a function for this, but preferring a more transparent approach.

Another possibility might be to actually assign a Void instance of the T response during initialization, and then I could grab the actual type from this ...

+5
source share
1 answer

Send a message: http://mydailyjava.blogspot.com/2013/06/advanced-java-generics-retreiving.html

Actually exactly what you are looking for.

Accordingly, you just need to extend your Response class, and then request the generic type of its super.

-1
source

Source: https://habr.com/ru/post/1246720/


All Articles