简体   繁体   中英

What is the point of NonNull annotation?

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).

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, eg, by an explicit null check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM