简体   繁体   中英

how to get a class reference to parameterized type

Is there any chance to assign to class reference the parameterized type eg.

    Class<Set>  c1= Set.class;   //OK
    Class<Set<Integer>> c2 = Set<Integer>.class; //Makes error

You can't do it this way, because the type-parameter information is gone at Runtime and the .class statement is actually evaluated then.

You can only do:

Set<Integer> someSet = ..
Class<?> c2 = someSet.class;

Using .class literal with a class name, or invoking getClass() method on an object returns the Class instance, and for any class there is one and only one Class instance associated with it.

Same holds true for a generic type. A class List<T> has only a single class instance, which is List.class . There won't be different class types for different type parameters. This is analogous to how C++ implements generics, where each generic type instantiation will have a separate Class instance. So in Java, you can't do Set<Integer>.class . Java doesn't allow that because it doesn't make sense, and might give wrong intentions about number of Class instances.

However, if you want a Class<Set<Integer>> , you can achieve that will a bit of type casting (which will be safe), as shown below:

Class<Set<Integer>> clazz = (Class<Set<Integer>>)(Class<?>) Set.class;

This will work perfectly fine.

new ParameterizedTypeReference<List<ClassName>>() {} Should work.

Example is giving below for exchange method Rest Template class exchange function

Funcation Requirement

public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException 

Implementation

restTemplate.exchange(new URI("Http://{host}:{port}/{url}"), HttpMethod.POST, customObject, new ParameterizedTypeReference<List<ResponseClassName>>() {});

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