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

Mon*_*omo 101 java compiler-construction android annotations android-studio

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

我得到的错误是这样的:

在此输入图像描述

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

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

mat*_*ash 118

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

protected void onSaveInstanceState(@NonNull Bundle outState)
Run Code Online (Sandbox Code Playgroud)

(并且)

import android.support.annotation.NonNull;
Run Code Online (Sandbox Code Playgroud)

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

@NonNull注释可以用来表示一个给定参数不能为空.

如果已知局部变量为null(例如,因为某些早期代码检查它是否为null),并将其作为参数传递给该参数标记为@NonNull的方法,IDE将警告您已有潜在的崩溃.

它们是静态分析的工具.运行时行为根本不会改变.


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

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
}
Run Code Online (Sandbox Code Playgroud)

  • 它的目的是什么? (5认同)
  • @IgorGanapolsky对不起,没有提到,因为我认为问题只是关于'NotNull` /`NonNull`的区别.相应调整后的答案. (2认同)
  • 换句话说,恕我直言,这个注释可以删除函数内部必要的空值检查,并具有更快的代码. (2认同)

Luk*_*iko 15

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

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

dependencies {
    compile 'com.android.support:support-annotations:20.0.0'
}
Run Code Online (Sandbox Code Playgroud)

您将收到警告,因为Bundle参数已使用@NotNull注释标记,并通过覆盖注释被隐藏的方法.正确的做法是将注释添加到overriden方法的参数中.

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
}
Run Code Online (Sandbox Code Playgroud)


nha*_*man 7

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

一个例子最好:

@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
}
Run Code Online (Sandbox Code Playgroud)

这些注释不会改变运行时行为(虽然我已经尝试过这个),但它可以作为防止错误的工具.

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

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
}
Run Code Online (Sandbox Code Playgroud)