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

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

提交回复
热议问题