简体   繁体   English

如何在Java中静态检查null指针异常?

[英]How can I static check the null pointer exception in Java?

There are some NullPointerException crashes in my Android project. 我的Android项目中有一些NullPointerException崩溃。 How can I static check or test the NullPointerException crash in Java / Android? 如何在Java / Android中静态检查或测试NullPointerException崩溃?

The correct way to avoid a nullPointerException at runtime is to surround your piece of code in a null check like this: 避免在运行时出现nullPointerException的正确方法是将代码片段包围在null检查中,如下所示:

if (mySomething != null) {
    doSomething(mySomething);
}

This will only use mySomething if it is not null and can be used, thereby avoiding nullPointerException s. 如果它不为null且可以使用,则只会使用mySomething ,从而避免了nullPointerException You can also catch a nullPointerExcepton , but this is not a good idea. 您还可以捕获 nullPointerExcepton ,但这不是一个好主意。


You can also use a static analysis tool like FindBugs or IntelliJ's built in inspections to analyze your code and tell you if it could produce a nullPointerException . 您还可以使用诸如FindBugs或IntelliJ的内置检查之类的静态分析工具来分析您的代码,并告诉您是否可能产生nullPointerException

There is a great article which describes best practices for the most common cases of NPE: http://javarevisited.blogspot.hu/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html 有一篇很棒的文章描述了NPE最常见情况的最佳实践: http : //javarevisited.blogspot.hu/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application html的

You could parametrize your code analyzer tool to catch these cases. 您可以参数化代码分析器工具以捕获这些情况。

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

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