问题就像标题一样简单。如何在Groovy中检查该对象是列表或集合或数组?但找不到一种简单的检查方法。有什么想法吗?
答案 0 :(得分:33)
List
是Collection
,因此检查不是互斥的:
def foo = ...
boolean isCollection = foo instanceof Collection
boolean isList = foo instanceof List
boolean isSet = foo instanceof Set
boolean isArray = foo != null && foo.getClass().isArray()
答案 1 :(得分:28)
我不知道您是否需要区分Collection,List和Array,或者只是想知道对象是否是这些类型的任何。如果是后者,你可以使用它:
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控制台中运行上面的代码,以确认其行为与宣传的一样
答案 2 :(得分:4)
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()
答案 3 :(得分:2)
我用它来“对象化”一个对象,如果它已经是一个集合,那么它将返回一个副本,否则将其包装在一个列表中。因此,您无需在处理时检查它,它始终是一个集合。
def arrayfy = {[] + it ?: [it]}
def list = arrayfy(object) // will be always a list
答案 4 :(得分:0)
只需使用instanceof运算符并检查对象是否是java.util.Collection的实例
答案 5 :(得分:0)
通常,您希望使用duck typing检查其行为。
def foo = someMethod()
if (foo.metaClass.respondsTo('each')) {
foo.each {println it}
}