简体   繁体   English

在Java中检查引用是否为null的最佳方法

[英]Best way to check if a reference is null in Java

I was wondring what the best way to check if we have a valid reference in java. 我想知道什么是最好的方法来检查我们是否在Java中有一个有效的引用。 I know that this syntax works, but its a mouth full. 我知道此语法有效,但令人难以置信。

if (myObj == null) {
  // Do something knowing we have an object
}

I'm coming from some other languages that allow you to just check a pointer like in c++. 我来自其他一些语言,这些语言使您可以像检查c ++一样检查指针。

char* prt = null;
if (ptr) {
  // We know we have a valid c-string 
}

Is there any equivocate or similar syntax in java? Java中是否有任何模棱两可或类似的语法? I would be okay using compiler extensions or a preprocessor. 使用编译器扩展或预处理程序我可以。

Follow up before. 继续跟进。 Before some one jumps in a starts talking about why I should just use the java syntax because you can forget an = sign please don't. 在开始讨论之前,我开始谈论为什么我应该只使用Java语法,因为您可能会忘记=符号,请不要这么做。

if (myObj = null) 

Will be caught by the compiler/linter. 将被编译器/ lint捕获。

Alas Java does not have an implicit conversion of the analogue of a nullptr_t or a pointer type to bool , so you have to use the somewhat more long-winded notation nullptr_t Java没有将nullptr_t的类似物或指针类型的隐式转换为bool ,因此您必须使用有点冗长的表示法

if (myObj == null)

whereas in C++ we can write 而在C ++中,我们可以编写

if (myObj)

In this respect, Java is less terse, and arguably clearer. 在这方面,Java不太简洁,而且可以说更清晰。

There is no shortcut syntax for dealing with null checks in Java, not even a null coalesce or null propagation operators available in other languages. 没有捷径语法可用于处理Java中的null检查,甚至没有其他语言中可用的空合并或空传播运算符。 There are no user-defined conversion operators either, so you wouldn't be able to use the C++ idiom that lets you write loops on expressions returning objects, eg while (cin >> x) { ... } . 也没有用户定义的转换运算符,因此您将无法使用C ++惯用语,该惯用语使您无法在返回对象的表达式上编写循环,例如while (cin >> x) { ... }

However, a powerful alternative exists in Java 8 to avoid null checks altogether: wrap your nullable objects in Optional<T> , and use its methods to hide null checks. 但是,Java 8中存在一个强大的替代方法,可以完全避免null检查:将可空对象包装在Optional<T> ,并使用其方法隐藏空检查。

Here is a short example: 这是一个简短的示例:

String s = "Hello";
Optional<String> os = Optional.ofNullable(s);
os.ifPresent(x -> { System.out.println(x); });

The above prints "Hello" . 上面打印 "Hello" If you set s to null , the code would print nothing. 如果将s设置为null ,则代码将不打印任何内容。

Oracle's article on using Optional<T> . Oracle有关使用Optional<T>的文章。

if(x == null) {
    doSomething();
}

... is the general idiom in Java. ...是Java中的通用习语。 Java's designers made the decision not to allow treating non-boolean variables as implicit "truthy" values. Java的设计者决定不允许将非布尔型变量视为隐式“真实”值。

Another common idiom is to use x == null in a ternary statement: 另一个常见的习惯用法是在三元语句中使用x == null

return x == null ? "not found" : x;

Or to use a standard method to throw an exception early on nulls: 或使用标准方法在null早期引发异常:

Objects.requireNonNull(x);

More generally, try to adopt a programming style in which you never expect null to be passed, and therefore don't have to code for the possibility. 更一般而言,尝试采用一种编程样式,在这种编程样式中您永远不会期望传递null,因此不必为这种可能性编写代码。

On non-public APIs, since you never pass a null, you never need to test for null (if a NullPointerException occurs, whoever passed the null can take responsibility for the mess themselves). 在非公共API上,由于您永远不会传递null,因此您无需测试null(如果发生NullPointerException ,则传递null的人都可以自己负责混乱)。

In public APIs, it may be a courtesy to the caller to validate non-nulls at the point they are passed, but it's by no means essential in every case. 在公共API中,在传递非null时验证调用者是否有礼貌,但这在每种情况下都不是必不可少的。

A reasonable goal is to always expect inputs to be non-null, and to never return a null (since Java 8, use Optional instead if necessary, or adopt the Null Object Pattern ). 一个合理的目标是始终期望输入为非null,并且永远不要返回null(因为Java 8,如有必要,请使用Optional ,或者采用Null Object Pattern )。

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

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