Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the .class of a Generics defined entity? [duplicate]

So how can I do the following in Java?

List<String> strings = new ArrayList<String>();       
JAXBElement<List<String>> jax = new JAXBElement<List<String>>(new QName("strings"), List<String>.class, strings);

The issue specifically occurs at List.class and the error returned is:

Multiple markers at this line
- List cannot be resolved to a variable
- String cannot be resolved to a variable
- Syntax error on token ">", void expected after this token
like image 386
Salsero69 Avatar asked Dec 03 '25 15:12

Salsero69


1 Answers

You can't.

The closest approximation to what you want is to use (Class<List<String>>) List.class.

This is because there is no List<String>.class, because at runtime, List<String>, List<Banana>, List<FruitSalad>, and List are all the same in Java. This is deliberately done for a whole bunch o' reasons, and it's called type erasure.

like image 188
Louis Wasserman Avatar answered Dec 06 '25 04:12

Louis Wasserman