简体   繁体   中英

Check if List is of one type or other

I have List<Zones> and List<Locations> and i am passing it to a generic function...

public String checkListType(List<?> checkList){
    // Now here I want to check if list is of type locations than
        return "locations"
    else {
        return "Zones";
    }
} 

This looks like an XY problem. I'll answer it as asked, but if you provide more information about what you're trying to do, I may have a better answer for you.

Generics in Java are not available at runtime; http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

You have a few options. You could pass the class into the method.

public <T> String checkListType(Class<T> clazz, List<T> checklist) {
   if ("Locations".equals(clazz.getName()) {
   } else if (...) {
   }
}

You could also use reflection to identify the type of the first element.

public String checkListType(List<?> checkList) {
   if (!checkList.isEmpty()) {
       Class<?> itemClass = checkList.get(0).getClass();
       if ("Locations".rquals(clazz.getName()) {
          ...
       }
   }
}

May this help.

public String checkListType(List<?> checkList){
    if( checkList == null || checkList.isEmpty() ) {
      return "UnKnown" ;
    }
    Object obj = checkList.get(0);
    if( obj instanceof Zones ) {
         return "Zones";
    } else if( obj instanceof Locations ) {
                 return "locations" ;
    }     
    else {
      return "Unknown";   
    }
} 

If you change the signature of the method to add a new parameter, you can use the Super Type Token pattern to identify the type parameter at runtime. Both super type tokesn and Class<T> can differentiate Locations from Zones . However, super type tokens are more powerful because they can can differentiate Set<Locations> from Set<Zones> as well.

Guava provides an implementation of TypeToken .

public <T> String checkListType(List<T> checkList, TypeToken<T> typeToken) {
    if (typeToken.equals(TypeToken.of(Locations.class))) {
        return "Locations";
    } else {
        return "Zones";
    }
}

Generics are implemented using type erasure so you cannot do so easily. If the lists are known to be non-empty, you could do something like

public String checkListType(List<?> checkList){
    Object first = checkList.get(0);
    if (first instanceof Locations) {
        return "locations"
    else {
        return "Zones";
    }
} 

But this is A Very Bad Idea.

From Effective C++, by Scott Meyers :

Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.

quoted from http://www.javapractices.com/topic/TopicAction.do?Id=31

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM