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

前端 未结 6 803
情书的邮戳
情书的邮戳 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: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

提交回复
热议问题