Android Studio错误的含义:未注释的参数覆盖@NonNull参数 [英] Meaning of Android Studio error: Not annotated parameter overrides @NonNull parameter

查看:9651
本文介绍了Android Studio错误的含义:未注释的参数覆盖@NonNull参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试用Android Studio。在创建一个新项目并添加一个默认的 onSaveInstanceState 方法到创建MyActivity类时,当我尝试提交代码到Git,我得到一个奇怪的错误,我不明白。代码如下:





我得到的错误是:





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


解决方案

这是一个注释,但是正确的名字是 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);
}

这篇关于Android Studio错误的含义:未注释的参数覆盖@NonNull参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆