Get type of generic type inside a List in Java

前端 未结 7 2392
再見小時候
再見小時候 2021-02-15 22:58

I have the below function:


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


        
7条回答
  •  北荒
    北荒 (楼主)
    2021-02-15 23:40

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

    public  void putList(String key, List list, Class 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 {
        private List 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.

提交回复
热议问题