Right way to use the @NonNull annotation in Android Studio

前端 未结 3 970
甜味超标
甜味超标 2020-12-29 22:20

I\'d like to use the @NonNull annotation in Android, but I can\'t figure out just the right way to do it. I propose you this example:

public voi         


        
相关标签:
3条回答
  • 2020-12-29 22:23

    Google examples do it as follows

    import static com.google.common.base.Preconditions.checkNotNull;
    
    ...
    
    public void doStuff(@NonNull String sParm){
         this.sParm= checkNotNull(s, "sParm cannot be null!");
    }
    
    0 讨论(0)
  • 2020-12-29 22:37

    You can use the comment-style suppression to disable that specific null check warning, e.g.:

        public MyMethod(@NonNull Context pContext) {
            //noinspection ConstantConditions
            if (pContext == null) {
                throw new IllegalArgumentException();
            }
            ...
        }
    

    You'll need that //noinspection ConstantConditions every time you do it.

    0 讨论(0)
  • 2020-12-29 22:43

    You can use Objects.requireNonNull for that. It will do the check internally (so the IDE will not show a warning on your function) and raise a NullPointerException when the parameter is null:

    public MyMethod(@NonNull Context pContext) {
        Objects.requireNonNull(pContext);
        ...
    }
    

    If you want to throw another exception or use API level < 19, then you can just make your own helper-class to implement the same check. e.g.

    public class Check {
        public static <T> T requireNonNull(T obj) {
            if (obj == null)
                throw new IllegalArgumentException();
            return obj;
        }
    }
    

    and use it like so:

    public MyMethod(@NonNull Context pContext) {
        Check.requireNonNull(pContext);
        ...
    }
    
    0 讨论(0)
提交回复
热议问题