Java 如何检查多个对象的无效性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31582524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:16:19  来源:igfitidea点击:

How to check multiple objects for nullity?

javanullnullable

提问by Krzysztof Wolny

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.:

我想知道是否有任何广泛使用的库(Google、Apache 等)可以一次检查多个对象的无效性,例如:

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

or

或者

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

UPDATE:

更新:

  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){
        //...
    }
    
  1. 我完全知道如何自己写
  2. 我知道这可能是程序结构不佳的结果,但这里不是这种情况
  3. 让我们让它更具挑战性,并用以下内容替换原始示例:

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

UPDATE 2:

更新 2:

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

我为 Apache Commons Lang 库创建了一个 pull request 来解决这个差距:

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

这些将包含在 commons-lang 3.5 版中:

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

采纳答案by Petr Jane?ek

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

编辑 2018:从 Apache Commons lang 3.5 开始,已经有ObjectUtils.allNotNull()ObjectUtils.anyNotNull().



No.

不。

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

的无Apache的百科全书郎(3.4) 谷歌番石榴(18)弹簧(4.1.7)提供了这样的工具方法。

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.

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

回答by tobias_k

In Java 8, you could use Stream.allMatchto check whether all of the values match a certain condition, such as being null. Not much shorter, but maybe a bit easier to read.

在 Java 8 中,您可以使用Stream.allMatch检查所有值是否匹配某个条件,例如 is null。不会更短,但可能更容易阅读。

if (Stream.of(a, b, c).allMatch(x -> x == null)) {
    ...
}

And analogeously for anyMatchand noneMatch.

并类推为anyMatchnoneMatch



About your "more challenging example": In this case, I think there is no way around writing a lazy-evaluated conjunction of null-checks, like the one you have:

关于你的“更具挑战性的例子”:在这种情况下,我认为没有办法编写一个惰性评估的空检查联合,就像你所拥有的那样:

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

Any of the other approaches, using streams, lists, or var-arg methods, would try to evaluate a.getFoo()before ahas been tested not to be null. You could use Optionalwith mapand method pointers, that will be lazily evaluated one after the other, but whether this makes it any more readable is debatable and may vary from case to case (particularly for longer class names):

使用流、列表或 var-arg 方法的任何其他方法都会尝试a.getFoo()a经过测试之前评估不是null. 您可以使用Optionalwithmap和方法指针,这将被一个接一个地懒惰评估,但这是否使其更具可读性是有争议的,并且可能因情况而异(特别是对于较长的类名):

if (Optional.ofNullable(a).map(A::getFoo).map(B::getBar).isPresent()) {
    ...
}

Bar bar = Optional.ofNullable(a).map(A::getFoo).map(B::getBar).orElse(null);

Another alternative might be to tryto access the innermost item, but I have a feeling that this is not considered good practice, either:

另一种选择可能是try访问最里面的项目,但我觉得这也不是一种好的做法:

try {
    Bar bar = a.getFoo().getBar();
    ...
catch (NullPointerException e) {
    ...
}

Particularly, this will also catch any other NPEs afteraccessing that element -- either that, or you have to put only the Bar bar = ...in the tryand everything else in another ifblock after the try, nullifying any (questionable) gains in readability or brevity.

特别是,这也将访问该元素捕获任何其他 NPE - 或者您必须仅将Bar bar = ...intry和其他所有内容放在if之后的另一个块中try,从而使可读性或简洁性方面的任何(有问题的)收益无效。



Some languages have a Safe Navigation Operator, but it seems like Java is not one of them. This way, you could use a notation like a?.getFoo()?.getBar() != null, where a?.getFoo()will just evaluate to nullif ais null.

有些语言有一个Safe Navigation Operator,但似乎 Java 不是其中之一。这样,您可以使用诸如a?.getFoo()?.getBar() != null, wherea?.getFoo()将评估为nullif ais 之类的符号null

回答by kamwo

You could also use something like the following method. It allows you to pass as many parameters as you want:

您也可以使用类似于以下方法的方法。它允许您传递任意数量的参数:

public static boolean isAnyObjectNull(Object... objects) {
    for (Object o: objects) {
        if (o == null) {
            return true;
        }
    }
    return false;
}

You call it with as many parameters as you like:

您可以使用任意数量的参数调用它:

isAnyObjectNull(a, b, c, d, e, f);


You could do something similar for areAllNull.

你可以为areAllNull.

public static boolean areAllObjectsNull(Object... objects) {
    for (Object o: objects) {
        if (o != null) {
            return false;
        }
    }
    return true;
}

Note: you could also use the ternary operator instead of if (o == null). The two methods shown here have no error handling. Adjust it to your needs.

注意:您也可以使用三元运算符代替if (o == null). 此处显示的两种方法没有错误处理。根据您的需要进行调整。

回答by silentprogrammer

You can create a list of you objects and use yourList.contains(null)in it.

您可以创建一个对象列表并yourList.contains(null)在其中使用。

List < Object > obList = new ArrayList < Object > ();

String a = null;
Integer b = 2;
Character c = '9';

obList.add(a);
obList.add(b);
obList.add(c);

System.out.println("List is " + obList);

if (obList.contains(null)) {
    System.out.println("contains null");
} else {
    System.out.println("does not contains null");
}

DEMO

演示

回答by viavad

It is possible with help of Objects class

在 Objects 类的帮助下是可能的

public static void requireNonNull(Object... objects) {
    for (Object object : objects) {
        Objects.requireNonNull(object);
    }
}