如何检查Groovy的对象是一个列表或集合或数组? [英] How to check in Groovy that object is a list or collection or array?

查看:130
本文介绍了如何检查Groovy的对象是一个列表或集合或数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题和标题一样简单。如何检查Groovy的对象是一个列表或集合或数组?但是找不到一个简单的方法来检查它。任何想法?

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?

推荐答案

我不知道你是否需要区分Collection,List和Array,如果对象是任何这些类型。如果是后者,你可以使用:

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")

在Groovy控制台中运行上面的代码,确认它的行为符合广告

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

这篇关于如何检查Groovy的对象是一个列表或集合或数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆