28

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 void doStuff(@NonNull String s){
     //do work with s...    
}

So when i call doStuff(null) the IDE will give me a warning. The problem is that I cannot rely on this annotation since, like this question points out, they don't propagate very far. So I'd like to put a null check on my method, like this:

 if(s==null) throw new IllegalAgrumentException();

But the IDE, assuming that s!=null, will warn me that s==null is always false. I'd like to know what is the best way to do this.

I personally think that there should be an annotation like @ShouldntBeNull that only checks and warns that null isn't passed to it, but doesn't complains when the value is null checked.

Community
  • 1
  • 1
MMauro
  • 687
  • 2
  • 6
  • 14
  • 1
    "I'd like to know what is the best way to do this" -- there should be a quick-fix in the IDE to suppress that warning. "I personally think..." -- you can [file a feature request](https://code.google.com/p/android/issues/list), if you like. – CommonsWare Sep 18 '15 at 12:48
  • @CommonsWare There doesn't seem to be a quick `SuppressWarning` fix in Android Studio 1.3.2 – MMauro Sep 18 '15 at 13:00
  • Well, that stinks. :-( – CommonsWare Sep 18 '15 at 13:02
  • 1
    Anyway I did as you suggested and filed a feature request. You can find it [here](https://code.google.com/p/android/issues/detail?id=186912) – MMauro Sep 18 '15 at 15:29

3 Answers3

13

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);
    ...
}
TmTron
  • 17,012
  • 10
  • 94
  • 142
8

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!");
}
user60108
  • 3,270
  • 2
  • 27
  • 43
7

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.

Darrell
  • 1,945
  • 15
  • 21