Andrzej Marciniak
Andrzej Marciniak

Reputation: 249

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

Upvotes: 17

Views: 13042

Answers (3)

Swarit Agarwal
Swarit Agarwal

Reputation: 2648

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>>() {});

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213223

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.

Upvotes: 15

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

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;

Upvotes: 3

Related Questions