由于Java泛型的实现方式,在大多数情况下,泛型信息会在运行时丢失.这些所谓的reifiable类型的例外之一是泛型类的具体扩展.对于第一个示例:
public class Video {
@Key
private String title;
public String getTitle() {
return title;
}
}
public class Response {
@Key
private TResult result;
public TResult getResult() {
return result;
}
// ...
}
解析器将无法反序列化result属性,因为它无法确定它是什么类型(因为此信息在运行时不可用).基本上,解析仅看到java.lang.Object,无法确定实例化将JSON数据放入的类型.我假设您已经怀疑是这种情况,因此尝试进行此调用:
Response videoResponse = parser.parse(reader, Response.class);
在上面的代码行中,您试图告诉解析器使用Video对特定的响应进行了参数化,但是不幸的是Java没有通用类文字的语法,因此代码无法编译.
在第二个示例中:
public class VideoResponse extends Response {
}
Response videoResponse = parser.parse(reader, VideoResponse.class);
您已经创建了泛型类的具体扩展.对于此类扩展,泛型类型信息在运行时可用,因此解析器可以确定需要实例化什么以反序列化JSON数据.
所有这些都是您实际问题的背景信息:
My question is: How to pass Response class to parse method as parameter without creating VideoResponse like that
您忽略了要使用的JSON库,但是在大多数流行的库中,反序列化方法具有重写的版本,可以接受通常称为超类型令牌的版本.超级类型令牌基本上只是类的具体扩展,类似于我上面所描述的.例如,在杰克逊,您将像这样反序列化JSON:
Response response = new ObjectMapper().readValue(
jsonString, // JSON data
new TypeReference>() {} // super type token, implemented by anonymous class
);
您应该检查JSON库文档中是否有类似内容.