简体   繁体   English

如何检查参数是否为空

[英]How to check if a parameter is null

I'm trying to test for null parameters but you cannot compare an object to null. 我正在尝试测试null参数,但无法将对象与null进行比较。

The following is dead code: 以下是无效代码:

    } else if(x == null){
        throw new NullPointerException("Parameter is null");
    }

How do I rewrite it to gain the desired effect? 如何重写以获得预期的效果?

To use handle in the Java literal sense of the word 在Java字面意义上使用handle

Foo foo = bar.couldReturnNull();
try {
   foo.doSomething();
} catch (NullPointerException e) {
   System.out.println("bar.couldReturnNull() returned null");
   throw new NullPointerException();
}

In Java you can compare to the value null. 在Java中,您可以将其与null值进行比较。 The standard way to do this is as follows: 执行此操作的标准方法如下:

String s = null;
if(s == null)
{  
    //handle null
}  

Typically throwing an NPE is a poor practice in the real world. 通常,在现实世界中,扔NPE是一种不良做法。

You don't say explicitly, but this looks like Java because of the NullPointerException. 您没有明确地说,但是由于NullPointerException,它看起来像Java。 Yes, you can compare an object reference to null, and so this code is fine. 是的,您可以将对象引用与null进行比较,因此此代码很好。 You might be mixing it up with SQL, where nothing compares equal to null. 您可能将其与SQL混为一谈,其中没有什么比等于null更好。

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

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