Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check what type a list class is of in java

Given that I have a

Class<?> clazz

I want to verify if clazz is a list of my specific object

So I started with

if (List.class.isAssignableFrom(type)) {

}

but up till here I only verified that it is List<?>. How can I verify for example it is a List<String>?

like image 775
mangusbrother Avatar asked Mar 12 '23 22:03

mangusbrother


1 Answers

You can't. Due to the nature of generics, at runtime the type information is erased. If you have an empty List, you can't tell anything for sure. If it's non-empty, you can check the first element and see if it's a String. That of course won't tell whether it's a List<String>, List<CharSequence> or a raw list.

What do you intend to do with the information if you get it? There's bound to be a better approach.

like image 178
Kayaman Avatar answered Mar 24 '23 01:03

Kayaman