Check ArrayList for instance of object

前端 未结 5 1333
南方客
南方客 2021-01-02 11:57

I have a java method that should check through an ArrayList and check if it contains an instance of a given class. I need to pass the method the type of class to check for a

5条回答
  •  悲哀的现实
    2021-01-02 12:48

    You can iterator over your list and test each element

    Class zz = String.class;
    for (Object obj : list) {
        if (zz.isInstance(obj)) {
            System.out.println("Yes it is a string");
        }
    }
    

    Note that isInstance also captures subclasses. Otherwise see Bela`s answer.

提交回复
热议问题