简体   繁体   English

如何在Java中没有null检查的情况下避免NullpointerException

[英]How to avoid NullpointerException without null check in java

In below code I would like to skip null check. 在下面的代码中,我想跳过空检查。 Please let me know the alternate solution. 请让我知道替代解决方案。

 public class NullCheck {



    public static void main(String[] args) {

        String str=args[0];

        if (null != str) //without using this null check how to avoid null pointer exception

        {
            System.out.println("Null check");
        }
        else

        {
            System.out.println("Null value");
        }
    }
}

Thanks 谢谢

You can avoid many null checks by using Yoda Expressions , for example 例如,可以使用Yoda Expressions避免许多空检查。

if ("Hello".equals(str))

"Hello" , as a literal, is never null and the built-in equals method will check str for null-ness. 作为文字, "Hello"绝不会为null ,并且内置的equals方法将检查str是否为空。 The alternative str.equals("Hello") would require you to check str first. 另一种str.equals("Hello")将要求您首先检查str

Some folk find them obfuscating, and it's not always possible to arrange your syntax accordingly. 有些人发现它们令人困惑,因此不一定总是可以相应地安排语法。

I guess theres something like a homework to do? 我猜想要做些功课吗? Eventually the teacher wants you to use a Try Catch Block? 最终,老师希望您使用“尝试捕获块”吗?

try{
   //what you want to do when its not null
}
catch (NullPointerException exp){
   //what happens if its null
}

It try's to perform the code in the Try block, but if a NullPointerException occurs, you can handle it in the Catch block. 它尝试在Try块中执行代码,但是如果发生NullPointerException,则可以在Catch块中进行处理。 Maybe, just maybe thats what you want. 也许,也许就是您想要的。

I skipped a null check in your code. 我跳过了您代码中的空检查。 No value is checked for null, whatsoever. 不会检查任何值是否为null。

public class NullCheck {

    static String str;

    public static void main(String[] args) {
    }
}

On more serious note, you could: 更严重的是,您可以:

  • explain why you want to avoid null check, 解释为什么要避免空检查,
  • initialize static String str to = ""; static String str初始化为= ""; (an empty string) and it will not be null for sure (just make sure that noone can assign null to it)!. (一个空字符串),并且它肯定不会为null (只需确保没有人可以为其分配null)!

Another alternate solution would to always initialize your variables to something. 另一种替代解决方案是始终将变量初始化为某种形式。 For stings, this could be an empty string: String string = ""; 对于字符串,这可能是一个空字符串: String string = ""; . For collections, this could be to initialize to empty collections: Collection<T> collection = Collections.emptyList(); 对于集合,这可能是初始化为空集合: Collection<T> collection = Collections.emptyList(); or Collection<T> list = new ArrayList<>() if you want to add to it at a later stage. Collection<T> list = new ArrayList<>()如果要在以后添加到Collection<T> list = new ArrayList<>()

The problem however, is that at some point, you will need to see if an object is null since not every object has some default, safe initialization value: 但是问题是,在某个时候,您将需要查看对象是否为空,因为并非每个对象都具有一些默认的安全初始化值:

Scanner scanner = null;

try
{
    scanner = new Scanner(...);
    ...
}
...
finally
{
    if(scanner != null) scanner.close();
}

Thus, I do not think that you can completely avoid having to make null checks, but you can mitigate it. 因此,我认为您不能完全避免进行空检查,但是可以减轻它的负担。

我不知道您的检查有什么问题,这似乎是很好的解决方案,但是您可以使用try-catch语句,或者通过默认值“”初始化str对象并检查空字符串,或者使用断言来检查可为空的对象。

Short answer: you can't. 简短的答案:您不能。 Long answer: you can with workarounds, which effectively will be what checking if-else for null is. 长答案:您可以使用解决方法,这实际上就是检查if-else是否为null的方法。

Some already provided their answers, i'll give you a tip (not really an answer, since it actually does the opposite): Java 8 introduced generic class: Optional 有些已经提供了答案,我将给您一个提示(不是真正的答案,因为它实际上是相反的):Java 8引入了通用类: 可选

It internally holds a reference to an object or null. 它在内部保存对对象的引用或null。 What it gives you is that whenever you would try to invoke a method on the object it holds, to get to the actual object you need to call get() method, which will more likely remind you about checking for existence. 它为您提供的是,每当您尝试对其所持有的对象调用一个方法时,要到达实际的对象,您都需要调用get()方法,这将更有可能提醒您检查是否存在。

Just a small sample: 只是一个小样本:

package whatever;
import java.util.Optional;

public class Main(){
    public static void main(String[] args) {
        Optional<String> a = Optional.empty();
        Optional<String> b = Optional.ofNullable(notReallyAString);
        Optional<String> c = Optional.of("John Paul II");
        if(a.isPresent()) System.out.println("Empty optional, you shouldnt be able to see this");
        if(b.isPresent()) System.out.println("Optional with a null, shouldnt be able to see this");
        if(c.isPresent()) System.out.println(c.get());  
    }
}

Note however, it is not supposed to be a general-purpose-any-value-volder, you'll more likely only want to use Optional only as a return type of a method to say to the client, that it might be indeed null. 但是请注意,它不应该是通用的任何值范围,您更有可能只希望将Optional仅用作要对客户端说的方法的返回类型,它可能确实为null 。

Remember, that trying to get (by get() method) the null element inside the Optional instance will result the NoSuchElementException immediately (but it's still unchecked exception) 请记住,尝试(通过get()方法)获取Optional实例内的null元素将立即导致NoSuchElementException(但它仍然是未经检查的异常)

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

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