简体   繁体   English

在 Java 中检查 String 的值是否为 null 的最佳方法

[英]Best method to check if a value of a String is null in Java

there are many implementation in how to check whether a String value is null and I'm really confused what to use!关于如何检查 String 值是否为 null 的实现有很多,我真的很困惑该用什么!

These are my searches so far:到目前为止,这些是我的搜索:

  1. if(myString == null){}

  2. Objects.equals(null, myString);

  3. ObjectUtils.isEmpty(myString)

  4. myString.equals(null)

  5. myString.compareTo(null);


NOTE: This is all about performance, reliable coding, fail-safe and other security purposes!注意:这都是关于性能、可靠编码、故障安全和其他安全目的!

Updated: myString is dynamic, what if it was null, some of the implementation above will throw NullPointerException!更新: myString 是动态的,如果它是 null 怎么办,上面的一些实现会抛出 NullPointerException!

Just use a simple == .只需使用一个简单的== There's no need to overcomplicate this.没有必要将其复杂化。

Another Option if you are using Java 8 you can use Optional::ofNullable另一种选择,如果您使用的是 Java 8,则可以使用Optional::ofNullable

Optional.ofNullable(myString).isPresent()// true if not null, false if null

You can even use:你甚至可以使用:

Optional.ofNullable(myString)
        .orElseThrow(() -> new Exception("If null throw an exception"));

There are many Options, just read the documentation有很多选项,只需阅读文档


But as Mureinik mention in his answer == is enough in your case.但正如Mureinik在他的回答中提到的那样==对你来说就足够了。

  1. if(myString == null)

    Easiest and right way.最简单正确的方法。

  2. Objects.equals(null, myString)

    A right way, its implemention is based on 1.一个正确的方法,它的实现基于1。

  3. ObjectUtils.isEmpty(myString)

    Not sure which ObjectUtils you are working with, but it seems to check myString is empty, not null.不确定您正在使用哪个ObjectUtils ,但它似乎检查myString是否为空,而不是 null。

  4. myString.equals(null)

    This does not work when myString is null, NPE will be thrown.myString为 null 时,这不起作用,将抛出 NPE。

  5. myString.compareTo(null)

    This does not work when myString is null, NPE will be thrown.myString为 null 时,这不起作用,将抛出 NPE。

` `

String results;
if(results==null ||results.length()==0) {

}

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM