避免!= null语句 [英] Avoiding != null statements

查看:80
本文介绍了避免!= null语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 object!= null 以避免 NullPointerException

I use object != null a lot to avoid NullPointerException.

是否有这个的好选择?

Is there a good alternative to this?

例如:

if (someobject != null) {
    someobject.doCalc();
}

这可以避免 NullPointerException ,当不知道对象是否 null 时。

This avoids a NullPointerException, when it is unknown if the object is null or not.

请注意,接受的答案可能是日期,请参阅 https://stackoverflow.com/a/2386013/12943 以获取更新的方法。

Note that the accepted answer may be out of date, see https://stackoverflow.com/a/2386013/12943 for a more recent approach.

推荐答案

如果您使用(或计划使用)Java IDE,例如 JetBrains IntelliJ IDEA ,Eclipse或Netbeans或像findbugs这样的工具,那么你可以使用注释来解决这个问题。

If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.

基本上,你有 @Nullable @NotNull

您可以在方法和参数中使用,如下所示:

You can use in method and parameters, like this:

@NotNull public static String helloWorld() {
    return "Hello World";
}

@Nullable public static String helloWorld() {
    return "Hello World";
}

第二个例子不会编译(在IntelliJ IDEA中)。

The second example won't compile (in IntelliJ IDEA).

当您在另一段代码中使用第一个 helloWorld()函数时:

When you use the first helloWorld() function in another piece of code:

public static void main(String[] args)
{
    String result = helloWorld();
    if(result != null) {
        System.out.println(result);
    }
}

现在IntelliJ IDEA编译器会告诉你检查没用,因为 helloWorld()函数不会返回 null

Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.

使用参数

void someMethod(@NotNull someParameter) { }

如果您写的内容如下:

someMethod(null);

这不会编译。

最后一个例子使用 @Nullable

@Nullable iWantToDestroyEverything() { return null; }

这样做

iWantToDestroyEverything().something();

你可以肯定这不会发生。 :)

And you can be sure that this won't happen. :)

让编译器检查比平常更多的东西并强制你的合同更强大是一种很好的方法。不幸的是,它并没有得到所有编译器的支持。

It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.

在IntelliJ IDEA 10.5及更高版本中,他们增加了对任何其他 @Nullable @NotNull implements。

In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.

参见博文 更灵活,可配置的@Nullable / @NotNull注释

See blog post More flexible and configurable @Nullable/@NotNull annotations.

这篇关于避免!= null语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆