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

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

问题描述

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

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

什么可以替代:

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

推荐答案

如果您使用(或计划使用)诸如 JetBrains IntelliJ IDEA Eclipse

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.

您可以像这样使用in方法和参数:

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) { }

如果您编写类似这样的内容:

if you write something like:

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批注 .

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

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

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