繁体   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