如何检查多个对象是否无效? [英] How to check multiple objects for nullity?

查看:288
本文介绍了如何检查多个对象是否无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我可以看到如下代码构造:

Often, I can see a code constructs like following:

if(a == null || b == null || c == null){
    //...
}

我想知道是否有任何广泛使用的库(谷歌,阿帕奇等)同时检查多个对象的无效,例如:

I wonder if there is any widely used library (Google, Apache, etc.) to check against nullity for multiple objects at once, e.g.:

if(anyIsNull(a, b, c)){
    //...
}

if(allAreNulls(a, b, c)){
    //...
}

更新:


  1. 我完全知道如何自己写。

  2. 我知道这可能是穷人的结果程序结构,但这不是一个案例

  3. 让我们更具挑战性,用这样的东西取代原来的例子:

  1. I perfectly know how to write it by myself
  2. I know it can be the result of the poor program structure but it's not a case here
  3. Let's make it more challenging and replace original example with something like this:

if(a != null && a.getFoo() != null && a.getFoo().getBar() != null){
    //...
}


更新2:

我已经为Apache Commons Lang库创建了拉取请求以修复此差距:

I've created a pull request for Apache Commons Lang library to fix this gap:

  • Issue: https://issues.apache.org/jira/browse/LANG-781
  • PR: https://github.com/apache/commons-lang/pull/108

这些将被纳入commons-lang,版本3.5:

These will be incorporated in commons-lang, version 3.5:


  • anyNotNull (对象...值)

  • allNotNull(对象...值)

  • anyNotNull (Object... values)
  • allNotNull (Object... values)

推荐答案

EDIT 2018:从Apache Commons lang 3.5开始,已经有< a href =https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ObjectUtils.html#allNotNull-java.lang.Object...-的rel = noreferrer> ObjectUtils.allNotNull() ObjectUtils.anyNotNull()

EDIT 2018: As of Apache Commons lang 3.5, there has been ObjectUtils.allNotNull() and ObjectUtils.anyNotNull().

否。

Apache Commons Lang(3.4) Google Guava(18) Spring(4.1.7)提供了这样一种实用方法。

None of Apache Commons Lang (3.4), Google Guava (18) and Spring (4.1.7) provide such a utility method.

如果真的真的需要,你需要自己编写。在现代Java代码中,我可能会考虑需要这样的构造代码味道。

You'll need to write it on your own if you really, really need it. In modern Java code, I'd probably consider need for such a construct a code smell, though.

这篇关于如何检查多个对象是否无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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