ChatGPT解决这个技术问题 Extra ChatGPT

Android Studio错误的含义:未注释的参数覆盖@NonNull参数

我正在尝试 Android Studio。在创建新项目并向 create MyActivity 类添加默认 onSaveInstanceState 方法时,当我尝试将代码提交到 Git 时,我收到一个我不明白的奇怪错误。代码是这样的:

https://i.stack.imgur.com/bxyek.png

我得到的错误是这样的:

https://i.stack.imgur.com/qJYSE.png

如果我尝试将方法签名更改为 protected void onSaveInstanceState(@NotNull Bundle outState),那么 IDE 会告诉我它无法解析符号 NotNull

我需要做什么才能摆脱警告?


m
matiash

这是一个注释,但正确的名称是 NonNull

protected void onSaveInstanceState(@NonNull Bundle outState)

(并且)

import android.support.annotation.NonNull;

目的是允许编译器在违反某些假设时发出警告(例如,在这种特殊情况下,方法的参数应该始终具有值,尽管还有其他假设)。来自 Support Annotations 文档:

@NonNull 注释可用于指示给定参数不能为空。如果已知局部变量为空(例如,因为一些早期代码检查它是否为空),并且您将其作为参数传递给该参数标记为 @NonNull 的方法,IDE 将警告您有潜在的崩溃。

它们是静态分析的工具。运行时行为根本没有改变。

在这种情况下,特定警告是您正在覆盖的原始方法(在 Activity 中)在 outState 参数上有一个 @NonNull 注释,但您没有将它包含在覆盖方法中。只需添加它就可以解决问题,即

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
}

它的目的是什么?
@IgorGanapolsky 抱歉,没有提到这一点,因为我认为问题只是关于 NotNull/NonNull 的差异。相应地调整答案。
换句话说,恕我直言,这个注释可以消除函数内部的空值检查的必要性,并且具有更快的代码。
@JohnPang您可以,但是由于不能保证注释所暗示的限制实际上会得到执行,因此这可能不是一个好主意。
导入android.support.annotation.NonNull;找这个东西 2 小时......没有人提到如何导入 NonNull .. 因此投票
L
LukaCiko

最近在 Android 支持库中添加了许多有用的 support annotations。它们的主要作用是注释各种方法和参数的属性以帮助捕获错误。例如,如果您将 null 值传递给标有 NotNull 注释的参数,您将收到警告。

通过添加以下依赖项,可以使用 Gradle 将注释添加到您的项目中:

dependencies {
    compile 'com.android.support:support-annotations:20.0.0'
}

您收到警告是因为 Bundle 参数标有 @NotNull 批注,并且通过覆盖该批注隐藏的方法。正确的做法是将注释也添加到被覆盖方法的参数中。

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
}

n
nhaarman

除了其他答案之外,@NonNull(和它的对手,@Nullable)注释还注释了字段、参数或方法返回类型。 IntelliJ 和 Android Studio 可以在编译时警告您可能出现的 NullPointerException

这里最好举个例子:

@NonNull private String myString = "Hello";

@Nullable private String myOtherString = null;

@NonNull 
public Object doStuff() {
    System.out.println(myString.length); // No warning
    System.out.println(doSomething(myString).length); // Warning, the result might be null.

    doSomething(myOtherString); // Warning, myOtherString might be null.

    return myOtherString; // Warning, myOtherString might be null.
}

@Nullable
private String doSomething(@NonNull String a) {
    return a.length > 1 ? null : a; // No warning
}

这些注释不会改变运行时行为(尽管我有 experimented),而是作为防止错误的工具。

请注意,您收到的消息不是错误,而只是一个警告,如果您愿意,可以安全地忽略它。另一种方法是自己注释参数,正如 Android Studio 建议的那样:

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
}