java SonarQube 阻止程序问题 NullPointerException 可能会被抛出,因为这里的“联系人”可以为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40233277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:01:11  来源:igfitidea点击:

SonarQube Blocker Issue NullPointerException might be thrown as 'contacts' is nullable here

javasonarqube

提问by BeginnersSake

I have a method that returns list of contacts. When I am running this code on SonarQube server. It shows a blocker issue stating NullPointerException might be thrown as 'contacts' is nullable here.. How to resolve this?

我有一个返回联系人列表的方法。当我在 SonarQube 服务器上运行此代码时。它显示了一个阻止程序问题,指出NullPointerException 可能会被抛出,因为“联系人”在这里可以为空。. 如何解决这个问题?

    List<Contact> getContactDetails(){...}

    public void checkSize() {
      List<Contact> contacts = getContactDetails(); 
      syso(contacts.size()); 
    }

回答by Gernot R. Bauer

Depending on your implementation of getContactDetails(), this method might return null, and so the line

根据您的 实现getContactDetails(),此方法可能会返回null,因此该行

syso(contacts.size()); 

might fail due to an NPE because contactscould be null.

可能由于 NPE 而失败,因为contacts可能是null.

Fix this by either adding

通过添加来解决此问题

if(contacts != null) {
    syso(contacts.size()); 
} else {
    // exception, error handling or nothing
}

or by not returning nullin getContactDetails().

或者通过不返回nullgetContactDetails()

回答by walen

Sonar is complaining that you're calling .size()on something that might be null. So make sure you don't do that:

声纳抱怨您正在调用.size()可能是null. 因此,请确保您不要这样做:

List<Contact> getContactDetails(){...}

public void checkSize() {
  List<Contact> contacts = getContactDetails(); 
  syso(contacts == null ? "contacts is null" : contacts.size()); 
}