Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call .class for a class with type parameter? E.g. List<String>.class

Tags:

java

spring

To start with an easy example, calling List<String>.class results in compile error, I can just call List.class to achieve my purpose.

Recently, I am doing things related to Spring REST template. I have to input a class object for the getForObject method. I have such a class: Foo<T>.

The result is, I cannot provide Foo<Bar>.class as one of the arguments. Could anyone please help?

like image 341
user667113 Avatar asked Mar 25 '26 10:03

user667113


1 Answers

You can't do it, because at runtime there are no types, due to type erasure.

When the program executes, there is only List.class - there is no such thing as List<String>.class, just provide a List.class.

If you really need to pass the class of the type, change your method to accept a Class<T> parameter and pass String.class.

like image 138
Bohemian Avatar answered Mar 27 '26 00:03

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!