How to use @Nullable and @Nonnull annotations more effectively?

后端 未结 9 462
你的背包
你的背包 2020-12-12 12:01

I can see that @Nullable and @Nonnull annotations could be helpful in preventing NullPointerExceptions but they do not propag

9条回答
  •  难免孤独
    2020-12-12 12:49

    Compiling the original example in Eclipse at compliance 1.8 and with annotation based null analysis enabled, we get this warning:

        directPathToA(y);
                      ^
    Null type safety (type annotations): The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'
    

    This warning is worded in analogy to those warnings you get when mixing generified code with legacy code using raw types ("unchecked conversion"). We have the exact same situation here: method indirectPathToA() has a "legacy" signature in that it doesn't specify any null contract. Tools can easily report this, so they will chase you down all alleys where null annotations need to be propagated but aren't yet.

    And when using a clever @NonNullByDefault we don't even have to say this every time.

    In other words: whether or not null annotations "propagate very far" may depend on the tool you use, and on how rigorously you attend to all the warnings issued by the tool. With TYPE_USE null annotations you finally have the option to let the tool warn you about every possible NPE in your program, because nullness has become an intrisic property of the type system.

提交回复
热议问题