How to check in Groovy that object is a list or collection or array?

前端 未结 6 802
情书的邮戳
情书的邮戳 2021-02-05 01:31

The question is as simple as the title. How to check in Groovy that object is a list or collection or array? But can\'t find a simple way of checking it. Any ideas?

相关标签:
6条回答
  • 2021-02-05 01:36

    Just use the instanceof operator and check if the object is an instance of java.util.Collection

    0 讨论(0)
  • 2021-02-05 01:39

    If you are looking for a Groovy way, look at in operator. It is actually a combination of Class.isAssignableFrom(Class<?>) and Class.isInstance(Object) meaning that you can use it to test classes as well as objects.

    // Test classes
    assert ArrayList in Collection
    assert ArrayList in List
    assert HashSet in Collection
    assert HashSet in Set
    
    // Test objects
    def list = [] as ArrayList
    def set = [] as HashSet
    
    assert list in Collection
    assert list in List
    assert set in Collection
    assert set in Set
    

    Testing if an object is an array may be tricky. I would recommend @BurtBeckwith's approach.

    def array = [].toArray()
    
    assert array.getClass().isArray()
    
    0 讨论(0)
  • 2021-02-05 01:42

    I don't know if you need to distinguish between Collection, List and Array, or just want to know if an object is any of these types. If the latter, you could use this:

    boolean isCollectionOrArray(object) {    
        [Collection, Object[]].any { it.isAssignableFrom(object.getClass()) }
    }
    
    // some tests
    assert isCollectionOrArray([])
    assert isCollectionOrArray([] as Set)
    assert isCollectionOrArray([].toArray())
    assert !isCollectionOrArray("str")
    

    Run the code above in the Groovy console to confirm it behaves as advertised

    0 讨论(0)
  • 2021-02-05 01:44

    Usually you'd want to check its behavior with duck typing.

    def foo = someMethod()
    if (foo.metaClass.respondsTo('each')) {
      foo.each {println it}
    }
    
    0 讨论(0)
  • 2021-02-05 01:56

    A List is a Collection, so the checks aren't mutually exclusive:

    def foo = ...
    boolean isCollection = foo instanceof Collection
    boolean isList = foo instanceof List
    boolean isSet = foo instanceof Set
    boolean isArray = foo != null && foo.getClass().isArray()
    
    0 讨论(0)
  • 2021-02-05 02:00

    I use this to "arrayfy" an object, if its already a collection then it will return a copy, else wrap it in a list. So you don't need to check it while processing, it will be always a collection.

    def arrayfy = {[] + it ?: [it]}
    def list = arrayfy(object) // will be always a list
    
    0 讨论(0)
提交回复
热议问题