Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to use the @NonNull annotation in Android Studio

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.

like image 468
MMauro Avatar asked Sep 18 '15 12:09

MMauro


People also ask

What does @nonnull annotation do?

@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.

How do I use annotations in Android?

To enable annotations in your project, add the support-annotations dependency to your library or app. Any annotations you add then get checked when you run a code inspection or lint task.

What is @nullable annotation in Android?

The @Nullable annotation means that the given parameter or return value can be null, letting Android Studio warn you if you try to use a value that might be null without checking (such as our previous optional filter).

What is @nullable in Android Studio?

Denotes that a parameter, field or method return value can be null. When decorating a method call parameter, this denotes that the parameter can legitimately be null and the method will gracefully deal with it. Typically used on optional parameters.


1 Answers

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);     ... } 
like image 199
TmTron Avatar answered Sep 30 '22 13:09

TmTron