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

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

问题描述

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

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:

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

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?

推荐答案

是一个注解,但正确的名字是NonNull:

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

protected void onSaveInstanceState(@NonNull Bundle outState)

(还有)

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:

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

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

如果已知局部变量为空(例如因为某些较早的代码检查它是否为空),然后将其作为参数被标记为@NonNull 的方法,IDE 会警告您可能发生崩溃.

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.

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

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天全站免登陆