Get type of generic type inside a List in Java

前端 未结 7 2376
再見小時候
再見小時候 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:52

    It is not possible to determine this due to erasure, which means that the parameter is not stored in the code. However you can either pass an extra parameter specifying what type the list is:

    public  void putList(String key, List lst, Class listElementType) {
    

    }

    or you can determine the type of each element at runtime:

    public  void putList(String key, List lst){
      for (Object elem:lst) {
          if (elem instanceof String) {
          // Do something       
          }
          if (elem instanceof Integer) {
          // Do something   
          }
      }
    }
    

提交回复
热议问题