简体   繁体   中英

How can I determine the unerased type of a field?

I have a generic response wrapper class:

public class Response <T> {
    T response;
}

and unrelated classes to be wrapped:

public class ServiceResponse {
    String someField;
}

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

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

Now, all my service responses have the same outer wrapper, ie, 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 the appropriate instance, if the deserialization was done within Response , I could use:

response = new T(jsonParser);

However, I'm doing all of this from within a library that is driven by reflection, so I normally deserialize the whole tree with code like:

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

but, at this point my parseObject method can't correctly determine the 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 ?

Eventually, I may wind up having to create an annotation providing more details about how to deserialize the field, probably by providing a function to do it, but would prefer a more transparent approach.

Another possibility might be to actually assign a void instance of T to response at initialization time and then I could grab the actual type from that...

Check out this post: http://mydailyjava.blogspot.com/2013/06/advanced-java-generics-retreiving.html

It's actually exactly what you're looking for.

According to this, you'll just need to extend your Response class and then query the generic type of its super.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM