Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/7275091/how-to-check-in-groovy-that-object-is-a-list-or-collection-or-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...