Meaning of Android Studio error: Not annotated parameter overrides @NonNull parameter

后端 未结 3 946
天命终不由人
天命终不由人 2020-12-03 02:37

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

3条回答
  •  我在风中等你
    2020-12-03 03:08

    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);
    }
    

提交回复
热议问题