简体   繁体   中英

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)):

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)):

 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()); ?

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).

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?

Thx!

T is nothing but the placeholder for the actual type, which will be provided at runtime. Therefore, the compiler has no clue T is, and consequently would not allow you to do things like T.class , or 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.

Regarding the Jackson's TypeReference it's useful for Collections and parametrized classes, for instance:

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> .

Therefore, Class<T> is handy only when you're parsing a non-generic object of type T .

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