Java 代码检查显示返回 null 的方法从不为 null

标签 java android android-studio lint

我发现了一个有趣的 Lint 检查,但我无法解释。我知道 Java 中隐藏的疯狂的东西,所以我想了解这里发生了什么。也许我可以用 super Nerd 的知识给我的 friend 留下深刻的印象。

以下是有问题的代码 fragment :

public void awesomeMethod()
{    
    final int[] hungryPeople = getHungryPeople();

    if ( hungryPeople != null ) // <---- Lint says that this can never be null?
    {
         solveWorldHunger( true );
         tellEveryone( false );
    }
}

这是相关的(相关)方法:

public int[] getHungryPeople()
{
   // Get hungry people data from the class's Android Intent field
   final int[] values = mIntent.getIntArrayExtra( HUNGRY_PEOPLE );

   if ( null != values )
   {
        return Arrays.copyOf( values, values.length );
   }

   return null;
}

我在这里缺少什么吗?

最佳答案

您在方法外部返回 null,您需要在 getHungryPeople() 内部返回,以防 valuesnull.

public int[] getHungryPeople()
{
   // Get hungry people data from the class's Android Intent field
   final int[] values = mIntent.getIntArrayExtra( HUNGRY_PEOPLE );

   if ( null != values )
   {
        return Arrays.copyOf( values, values.length );
   }

   // if values is null, return null
   return null;
}

关于Java 代码检查显示返回 null 的方法从不为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27005835/

相关文章:

java - 使用tomcat登录后将请求从servlet转发到jsp

android - 当用户单击文本和图标时更改颜色的命令是什么

java - 如何在约束布局中以编程方式移动 View (按钮)?

android - 如何实现底部工作表

javascript - anchor 标签自动上传文件场景

java - 从表单中的 JSTL 部分检索参数

java - PostgreSQL 序列的 increment_by 如何与 Hibernate 的 allocationSize 一起工作?

android - 使用 OpenSL ES Android 同时播放多种音效

android - 为什么我的相对布局占据了全屏宽度

android-studio - Android Studio 3.2 Canary 14 Github 集成