如何在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
List
是一个Collection
,因此检查不是互斥的:A
List
is aCollection
, so the checks aren't mutually exclusive:我不知道您是否需要区分 Collection、List 和 Array,或者只是想知道某个对象是否属于这些类型中的任何一种。如果是后者,您可以使用以下命令:
在 Groovy 控制台中运行上面的代码以确认其行为如广告所示
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:
Run the code above in the Groovy console to confirm it behaves as advertised
如果您正在寻找 Groovy 方式,请查看
in
运算符。它实际上是Class.isAssignableFrom(Class)
和Class.isInstance(Object)
的组合,这意味着您可以使用它来测试类和对象。测试一个对象是否是数组可能很棘手。我会推荐@BurtBeckwith 的方法。
If you are looking for a Groovy way, look at
in
operator. It is actually a combination ofClass.isAssignableFrom(Class<?>)
andClass.isInstance(Object)
meaning that you can use it to test classes as well as objects.Testing if an object is an array may be tricky. I would recommend @BurtBeckwith's approach.
我用它来“arrayfy”一个对象,如果它已经是一个集合,那么它将返回一个副本,否则将其包装在一个列表中。所以处理时不需要检查它,它永远是一个集合。
I use this to "arrayfy" an object, if its already a collection then it will return a copy, else wrap it in a list. So you don't need to check it while processing, it will be always a collection.
通常您需要使用鸭子打字来检查其行为。
Usually you'd want to check its behavior with duck typing.
只需使用instanceof运算符并检查该对象是否是java.util.Collection的实例
Just use the instanceof operator and check if the object is an instance of java.util.Collection