方法调用可能会产生空点异常改造主体

2022-09-02 20:46:14

我正在使用Retrofit 2从我的API获取响应并将其值存储在我的常量中,如下所示

if(response.isSuccessful()) {
                    constant.banner_on = response.body().getBanner_on();
                    constant.int_on = response.body().getInt_on();
                    constant.int_click = response.body().getInt_click();
                }

它给了我所有三个警告,如下所示

方法调用getBanner_on可能会生成 java.lang.nullPointerException

我很困惑,无法解决此警告。让我知道,如果有人可以帮助我从中走出来。


答案 1

它只是一个警告,因为如果响应成功,它永远不会为空。您可以忽略它或环绕以删除警告。if(response.body() != null)

Ads ads = response.body();
if(ads != null){
    constant.banner_on = ads.getBanner_on();
    // and so on.
}

答案 2

使用很棒,但只有一行,更干净的方式是:if

constant.banner_on = ads != null ? ads.getBanner_on() : null;

如果您使用的是 Java 8,则可以在赋值之前执行断言

Ads ads = response.body();
assert ads != null;
constant.banner_on = ads.getBanner_on();

另一种方法是在赋值之前使用 Objects.requireNonNull():

constant.banner_on = Objects.requireNonNull(ads.getBanner_on());

这实际上主要是为参数验证而设计的。源代码注释:

/**
     * Checks that the specified object reference is not {@code null}. This
     * method is designed primarily for doing parameter validation in methods
     * and constructors, as demonstrated below:
     * <blockquote><pre>
     * public Foo(Bar bar) {
     *     this.bar = Objects.requireNonNull(bar);
     * }
     * </pre></blockquote>
     * 

关于这个问题的一个很好的答案就在这里。另请阅读本文以了解为什么我们需要显式检查


推荐