簡體   English   中英

獲取我無法弄清的空指針異常

[英]Getting null pointer exception that I can't figure out

我已經在這個問題上工作了一段時間。 我在以下函數中不斷收到一個空指針異常,myProfile變量是對另一個類的引用,該類在開始時已聲明為私有UserProfile myProfile,其中UserProfile是原始類,我相信這是我遇到的地方問題。:

public void saveProfile()
{
    if ((myProfile!=(null)) && !(myProfile.getName().isEmpty()))
    {
        profiles.put(myProfile.getName(), myProfile);
    }
}

如果myProfile不如您所說的為null ,請使用調試器檢查返回的myProfile.getName() 如果返回null,則無法在null引用上調用isEmpty

在任何有點( . )的地方,都可能會出現空指針異常。 例如,您檢查myProfile不為null,但是在嘗試.isEmpty()之前,不檢查myProfile.getName()是否不為null。

同樣,如果profiles為null,則在對其調用.put()時會得到null指針異常。

如下修改您的代碼。 它不會引起異常

public void saveProfile(){
    if ((myProfile!=null) && (myProfile.getName() != null) &&!(myProfile.getName().isEmpty())){
        profiles.put(myProfile.getName(), myProfile);
    }
}
public void saveProfile()
{
  if (myProfile!=null && myProfile.getName()!=null && !myProfile.getName().isEmpty())
  {
    if(profiles==null)
      profiles = makeAnInstanceOfProfiles();

    profiles.put(myProfile.getName(), myProfile);
  }
}

使用測試代碼(在啟用斷言的情況下運行):

public void saveProfile()
{
  assert(myProfile!=null):"null at myprofile";
  assert(myProfile.getName()!=null):"null at myprofile/getName";
  assert(profiles!=null) : "profiles is null";

  if (myProfile!=null && myProfile.getName()!=null && !myProfile.getName().isEmpty())
  {
    if(profiles==null)
      profiles = makeAnInstanceOfProfiles();

    profiles.put(myProfile.getName(), myProfile);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM