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

前端 未结 6 772
栀梦
栀梦 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:25

    Update: there are two possible scenarios here:

    1. You are determining if an object is a collection;

    2. You are determining if a class is a collection.

    The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection or Map will cover the Java Collections.

    Solution 1:

    public static boolean isCollection(Object ob) {
      return ob instanceof Collection || ob instanceof Map;
    }
    

    Solution 2:

    public static boolean isClassCollection(Class c) {
      return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
    }
    

    (1) can also be implemented in terms of (2):

    public static boolean isCollection(Object ob) {
      return ob != null && isClassCollection(ob.getClass());
    }
    

    I don't think the efficiency of either method will be greatly different from the other.

提交回复
热议问题