[英]What are a differences between Generic T, Class<T>, JavaType, TypeReference and ResolvedTypein java?
I try to write a generic data loader.我尝试编写一个通用数据加载器。 Here is the loader logic (code snippet 1 (CS1)):
这是加载器逻辑(代码片段 1 (CS1)):
public class Loader<T> {
private ObjectMapper objectMapper = new ObjectMapper();
public T getData(String testDataPath , Class<T> resultClassType) throws IOException {
return objectMapper.readValue(new File(testDataPath), resultClassType);
}
}
And here is the code snipper where I use the loader (code snippet 2 (CS2)):这是我使用加载程序的代码片段(代码片段 2 (CS2)):
String[] stringArray;
//Todo something
stringArray = new Loader<String[]>().getData("<path>", String[].class);
My first question is: if I pass the type information here in CS2: new Loader<String[]>()
why I can't use this generic information here: return objectMapper.readValue(new File(testDataPath), new T().getClass());
我的第一个问题是:如果我在 CS2 中传递类型信息:
new Loader<String[]>()
为什么我不能在此处使用此通用信息: return objectMapper.readValue(new File(testDataPath), new T().getClass());
? ?
And at this point I got confused of terms T, Class<> and other type related classes which are allowed to pass as second parameter in the readValue function in objectMapper (Class<>, JavaType, TypeReference, ResolvedType).在这一点上,我对术语 T、Class<> 和其他类型相关的类感到困惑,这些类允许在 objectMapper 的 readValue function 中作为第二个参数传递(Class<>、JavaType、TypeReference、ResolvedType)。
So can someone explain me why I can't use the T as I tried and what are the differences between Class<>, JavaType, TypeReference, ResolvedType?那么有人能解释一下为什么我不能像我尝试的那样使用 T 以及 Class<>、JavaType、TypeReference、ResolvedType 之间有什么区别?
Thx!谢谢!
T
is nothing but the placeholder for the actual type, which will be provided at runtime. T
只是实际类型的占位符,它将在运行时提供。 Therefore, the compiler has no clue T
is, and consequently would not allow you to do things like T.class
, or new T()
.因此,编译器不知道
T
是什么,因此不允许您执行T.class
或new T()
之类的操作。 But compiler can help you to ensure that where you expect to operate with type T
you'll really get T
, ie you code type-safe.但是编译器可以帮助您确保在您期望使用类型
T
进行操作的地方您将真正获得T
,即您的代码类型安全。
Regarding the Jackson's TypeReference
it's useful for Collections and parametrized classes, for instance:关于 Jackson 的
TypeReference
,它对 Collections 和参数化类很有用,例如:
new TypeReference<List<String>() {}
new TypeReference<Foo<Bar>() {}
If you were using Class<T>
, you'll not be able to provide information about parameters of the type: Class<List.class>
, Class<Foo.class>
.如果您使用的是
Class<T>
,您将无法提供有关以下类型参数的信息: Class<List.class>
、 Class<Foo.class>
。
Therefore, Class<T>
is handy only when you're parsing a non-generic object of type T
.因此,
Class<T>
仅在您解析T
类型的非泛型 object 时才有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.