泛型变量的类类型



我的数据结构看起来或多或少像这个

class ResponseWrapper<T> {
T response;
public ResponseWrapper(T response) {
this.response = response;
}
}

以及处理将响应从JSON读取到实际DTO的服务。

public class GenericService<T> {
public ResponseWrapper<T> read(String json, Class<T> clazz) throws Exception {
T response = new ObjectMapper().readValue(json, clazz);
return new ResponseWrapper<>(response);
}
}

我可以这样称呼它:

GenericResponse<SomeData> response = new GenericService<SomeData>().read("json value", SomeData.class)

我正在努力实现的是:

GenericResponse<SomeData> response = new GenericService<SomeData>().read("json value")

我想知道,这真的有可能吗?这显然不起作用

public ResponseWrapper<T> read(String json) throws Exception {
T response = new ObjectMapper().readValue(json, T.class);
return new ResponseWrapper<>(response);
}

否。这是不可能的。

Java泛型通过类型擦除工作。。。这意味着与泛型类型参数相关联的实际类在运行时不可用。如果代码需要知道该类,则需要显式传递Class对象。

是的,T.class是一个编译错误。

是的,没有办法得到T的类。

最新更新