How to check if an Object is a Collection Type in Java?

前端 未结 6 775
栀梦
栀梦 2020-12-12 18:49

By using java reflection, we can easily know if an object is an array. What\'s the easiest way to tell if an object is a collection(Set,List,Map,Vector...)?

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 19:16

    Java conveniently has the instanceof operator (JLS 15.20.2) to test if a given object is of a given type.

     if (x instanceof List) {   
        List list = (List) x;
        // do something with list
     } else if (x instanceof Collection) {
        Collection col = (Collection) x;
        // do something with col
     }
    

    One thing should be mentioned here: it's important in these kinds of constructs to check in the right order. You will find that if you had swapped the order of the check in the above snippet, the code will still compile, but it will no longer work. That is the following code doesn't work:

     // DOESN'T WORK! Wrong order!
     if (x instanceof Collection) {
        Collection col = (Collection) x;
        // do something with col
     } else if (x instanceof List) { // this will never be reached!
        List list = (List) x;
        // do something with list
     }
    

    The problem is that a List is-a Collection, so it will pass the first test, and the else means that it will never reach the second test. You have to test from the most specific to the most general type.

提交回复
热议问题