检查 Integer 值是否为 null 时出现 Java 异常

问题描述 投票:0回答:4

以下代码片段导致我的程序抛出空指针异常,我正在努力确定原因:

private void ...(){
    HierarchyForm hForm = (HierarchyForm)
    Integer id = hForm.getId();
    if (id != null && id.intValue() > 0){ <-- exception thrown here
        ...
    }
    .
    .
    .
}

当崩溃时,“id”的值为空。我知道这可能很简单,但我不明白为什么。

编辑:这是一个简短的程序,显示它失败了。似乎是 .intValue 比较的问题 http://ideone.com/e.js/H0Mjaf

编辑:我正在为 java 1.6.0_45 构建

java null nullpointerexception integer
4个回答
0
投票

如果 id 为空,该行不应抛出 NPE。

如果 && 的第一个操作数为 false,则不计算第二个操作数,结果只是 false。

请再次重新检查您的代码,并确保您在评估 id.intValue() 时在这一行获得 NPE。


0
投票

使用此格式并找到正确的解决方案:

String id = request.getParameter("id");

        if(id!=null && !id.toString().equalsIgnoreCase(""))
        {
            user.setId(Integer.parseInt(id));
            dao.updateUser(user);
        }
        else
        {
            dao.addUser(user);
        }

如果使用其他类型的格式:

String id = request.getParameter("id");

        if(id == null || id.isEmpty())
        {
            dao.addUser(user);
        }
        else
        {
            user.setId(Integer.parseInt(id));
            dao.updateUser(user);
        }

很简单,做一个空检查!用 if 语句包围你的对象,例如

Object mayBeNullObj = getTheObjectItMayReturnNull();

if (mayBeNullObj != null) 
   { 
     mayBeNullObj.workOnIt(); // to avoid NullPointerException
   }

但是,他们都给出了相同的结果。


0
投票

此行导致 NPE 的唯一方法是在

id.intValue()
元素上执行
null

如果

id.intValue()
为 false,Java 不会执行
id != null
,因为
&&
会缩短执行时间。

我怀疑你的代码实际上是这样的:

if (id != null & id.intValue() > 0) {

而它应该看起来像这样:

if (id != null && id.intValue() > 0) {

-3
投票

你需要这样写:

private void ...(){
  HierarchyForm hForm = (HierarchyForm)
  Integer id = hForm.getId();
  if (id != null)
     if (id.intValue() > 0){ <-- exception thrown here
     ...
     }
  }
  . 
  .
  .
}

好吧,我没有想到java中的“&&”有这种行为来解决第一个表达式,而第二个表达式仅在“true”时解决。

在这种情况下,当然,我同意同事的回应,并假设你已经正确发布了代码,我的猜测是它与并发访问同一对象hForm有关,某些方法可能正在分配hForm 或 id 为“null”。

© www.soinside.com 2019 - 2024. All rights reserved.