I don't get how the NonNull annotation is supposed to help. So, let's say I have this:
void noNullArg(@NonNull Object o)
{
// stuff
}
If I do this, I receive a warning about how 'o' might be null.
void foo()
{
Object o = null;
noNullArg(o);
}
But if I do this instead, I receive no warning at all.
void sendNull()
{
// Pass null and violate the annotation
foo(null);
}
void foo(Object o)
{
noNullArg(o);
}
That's a pretty trivial case that is not detected. To top it all off, the compiler seems to think that checking for null if @NonNull is set is unnecessary, when it's obviously not (it says the condition is always false).
The @NonNull Annotation The @NonNull annotation is the most important among all the annotations of the null-safety feature. We can use this annotation t0 declare non-null constraint anywhere an object reference is expected: a field, a method parameter or a method's return value.
@NonNull – The compiler can determine cases where a code path might receive a null value, without ever having to debug a NullPointerException. @ReadOnly – The compiler will flag any attempt to change the object.
What is Annotating? Annotating is any action that deliberately interacts with a text to enhance the reader's understanding of, recall of, and reaction to the text. Sometimes called "close reading," annotating usually involves highlighting or underlining key pieces of text and making notes in the margins of the text.
On the other hand, if the parameter is mark as @Nullable and we don't add null check inside the function, Android Studio will warn you with lint error and some visual hint. The @NonNull/@Nullable annotation can put in front of functions as well to indicate the return value nullability.
As you might know Null Pointer Exception is very common failure case of Java. when compile see code as second case it will show warning.
Due to the inherent complexity, flow analysis is best performed in small chunks. analyze one method at a time will make good performance and this advantage is that analyze will fast and compiler can warn you as you type.but the dark side is that analysis can't see which values are running between method(as parameter or return). That is the reason in third case it will not show any warning. As EJP says it will check runtime.
@NonNull means null is not a legal value.
Here the null annotation comes to important. By defining @NonNull annotation you can tell to the compiler that you don't want a null value in position.
but It's the caller's responsibility to never pass a null value, which is to be ensured, e.g., by an explicit null check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With