且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-15 19:31:00

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

  protected void onSaveInstanceState(@NonNull Bundle outState)

(以及)

  import android.support.annotation.NonNull; 

目的是允许编译器违反(例如方法的参数应该总是具有值,如在这种特定情况下,虽然有其他)。从支持注释文档:


@NonNull 注释可用于表示给定的参数
不能为空。



如果一个局部变量被认为是null(例如因为一些
更早的代码检查它是否为null),并将它作为
参数传递给一个方法标记为@NonNull,
IDE将警告您有可能的崩溃。


分析。运行时行为根本不会改变。






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

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


I'm trying out Android Studio. Upon creating a new project and adding a default onSaveInstanceState method to the create MyActivity class, when I try to commit the code to Git, I get a strange error I don't understand. The code is this:

The error I get is this:

If I try to change the method signature to protected void onSaveInstanceState(@NotNull Bundle outState), then the IDE tells me it can't resolve the symbol NotNull.

What do I need to do to get rid of the warning?

It's an annotation, but the correct name is NonNull:

protected void onSaveInstanceState(@NonNull Bundle outState)

(And also)

import android.support.annotation.NonNull;

The purpose is to allow the compiler to warn when certain assumptions are being violated (such as a parameter of a method that should always have a value, as in this particular case, although there are others). From the Support Annotations documentation:

The @NonNull annotation can be used to indicate that a given parameter can not be null.

If a local variable is known to be null (for example because some earlier code checked whether it was null), and you pass that as a parameter to a method where that parameter is marked as @NonNull, the IDE will warn you that you have a potential crash.

They are tools for static analysis. Runtime behavior is not altered at all.


In this case, the particular warning is that the original method you're overriding (in Activity) has a @NonNull annotation on the outState parameter, but you did not include it in the overriding method. Just adding it should fix the issue, i.e.

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