Get type of generic type inside a List in Java

前端 未结 7 2259
天命终不由人
天命终不由人 2021-02-15 23:01

I have the below function:


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


        
相关标签:
7条回答
  • 2021-02-16 00:01

    Generics are called "erasures" because they exist at compile time only and are removed by compiler. So, there is no way to determine the generic type of collection. The only way to do it for non-empty lists is to take the first element and determine its type.

    This is almost the same solution that was suggested by DJClayworth, but I think that there is no need to check each element of the list. If you are sure that the list is created with generics (new ArrayList() or new LinkedList() etc) all its element are guaranteed to be of the same type.

    0 讨论(0)
提交回复
热议问题