[英]How can I determine the unerased type of a field?
我有一个通用的响应包装类:
public class Response <T> {
T response;
}
和不相关的类包装:
public class ServiceResponse {
String someField;
}
当我发出服务请求时,我得到的JSON响应类似于:
{ "code":200, "response":{"someField":"some text"} }
现在,我所有的服务响应都有相同的外包装,即它们都有:
{ "code":200, "timestamp":"....", "response":... }
但是响应字段的实际格式/类型对于每个服务请求是不同的。 当我反序列化响应时,我需要知道response
字段的类型,以便我可以创建适当的实例,如果反序列化是在Response
中完成的,我可以使用:
response = new T(jsonParser);
但是,我在一个由反射驱动的库中执行所有这些操作,因此我通常使用以下代码反序列化整个树:
wrapper = deserializer.parseObject(Response<ServiceResponse>.class)
但是,此时我的parseObject方法无法正确确定T的类型。
我可以使用类似的东西:
Response<ServiceResponse> response = new Response<>();
Field field = response.getClass().getDeclaredField("response");
Type type = field.getGenericType();
然后告诉我response
是类型T
但我实际需要的是ServiceResponse
根据这个SO问题,我尝试将其作为ParameterizedType
转换,但实际上它似乎适用于Response<ServiceResponse>
类型的字段而不是其中的实际字段(并且因为type
无法转换为ParameterizedType
而失败)
有没有办法确定(在运行时)原始类型的response
?
最后,我可能最终需要创建一个注释,提供有关如何反序列化字段的更多详细信息,可能通过提供执行此功能的功能,但更喜欢更透明的方法。
另一种可能性是在初始化时将实际的T实例分配给响应然后我可以从中获取实际类型...
看看这篇文章: http : //mydailyjava.blogspot.com/2013/06/advanced-java-generics-retreiving.html
这正是你正在寻找的。
根据这个,你只需要扩展你的Response
类,然后查询它的超类的泛型类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.