Get the class of java.util.Arrays$ArrayList

前端 未结 3 1050
南方客
南方客 2021-01-26 16:49

How can I know the instance of java.util.Arrays$ArrayList. I\'ve tried this code snippet but it does not work at all :

if (myList instanceof Arrays)         


        
相关标签:
3条回答
  • 2021-01-26 17:04

    Why are you using Arrays ? You must use ArrayList like in this code

    if (myList instanceof ArrayList) {
        //Do something here.
    }
    
    0 讨论(0)
  • 2021-01-26 17:21

    java.util.Arrays$ArrayList is a private inner class of Arrays, returned by the Arrays.asList method.

    Since it's a private class there is no way to get access to the class in a way that it can be used with the instanceof operator. You can do this check using reflection however:

    Class<?> clazz = Class.forName("java.util.Arrays$ArrayList");
    // ...
    clazz.isAssignableFrom(myList)
    

    But I do not recommend doing that. It's a good practice to program against an interface. In this case the List interface defines the behavior of the object. The actual class of the object shouldn't matter.

    0 讨论(0)
  • 2021-01-26 17:21

    in case the list comes from Arrays#asList, the returned ArrayList is NOT java.util.ArrayList, therefore a comparison to this class will always fail.

    The question is, why do you need to know that it is exactly this implementation ? Maybe it is enough to check for java.util.List ?

    In general it is questionable why you need the instanceof operator at all, often there are other design solutions better.

    0 讨论(0)
提交回复
热议问题