Search code examples
javareflectioncollectionsgeneric-programming

To get datatype of list or Collection as method param using reflection


I have to create a method that has body something like below:

 public void anyMethod(List<?> dataList){
      for (Iterator<?> it = dataList.iterator(); it.hasNext();) {
           Object p = it.next();
           if(p instanceOf XYZ){
               //do something
           }

           if(p instanceOf MNO){
               //do something
           }
      }
 }

Now rather than fetching every entry one by one and then checking it whether its instance of any class every time , is there is any way to find the datatype of list elements before entring the loop and without fetching any element from list using reflection. My list contain elements of same dayatype. Eg it may be either List or List etc but bot the combine datatype. Thanks


Solution

  • In Java , there is no way to get the used type for the generic declaration, in your case you can achieve what you are looking for by getting the first element of your list :

    if(dataList.size()>0) {
       Object p = dataList.get(0);
    
      if(p instanceOf XYZ){
                   //do something
      }
    
      if(p instanceOf MNO){
               //do something
      }
    
    }