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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With