Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of generic type inside a List in Java

Tags:

java

generics

I have the below function:


    public <T> void putList(String key, List<T> lst){
          if (T instanceof String) {
          // Do something       
          }
          if (T instanceof Integer) {
          // Do something   
          }
    }

Inside this function, i want to know if <T> is String or Integer so i wonder if there is a way to discover its type? I used the above code but it generated error

Thank you in advance.

like image 536
Phu Nguyen Avatar asked Nov 11 '10 14:11

Phu Nguyen


2 Answers

You can not find the type of T as the type information is erased. Check this for more details. But if the list is not empty, you can get an element from the list and can find out using instanceof and if else

like image 189
Teja Kantamneni Avatar answered Nov 10 '22 13:11

Teja Kantamneni


It's not possible in Java due to erasure. What most people do instead is add a type token. Example:

public <T> void putList(String key, List<T> list, Class<T> listElementType) {
}

There are certain situations where reflection can get at the type parameter, but it's for cases where you've pre-set the type parameter. For example:

public class MyList extends List<String> {
    private List<String> myField;
}

In both of those cases reflection can determine the List is of type String, but reflection can't determine it for your case. You'd have to use a different approach like a type token.

like image 9
Brad Cupit Avatar answered Nov 10 '22 13:11

Brad Cupit