mangusbrother
mangusbrother

Reputation: 4156

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

Upvotes: 4

Views: 500

Answers (1)

Kayaman
Kayaman

Reputation: 73548

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.

Upvotes: 7

Related Questions