在 Java 中避免 NullPointerException [英] Avoiding NullPointerException in Java

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

问题描述

我经常使用 object != null 来避免 NullPointerException.

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

什么是替代方案:

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

推荐答案

如果您使用(或计划使用)Java IDE,例如 JetBrains IntelliJ IDEAEclipseNetbeans 或 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.

Basically, you've got @Nullable and @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 实现的支持.

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

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

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

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