Which @NotNull Java annotation should I use?

前端 未结 22 3210
梦如初夏
梦如初夏 2020-11-22 02:44

I\'m looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions.

22条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 03:23

    If you are working on a big project, you may be better of creating your own @Nullable and/or @NotNull annotations.

    For example:

    @java.lang.annotation.Documented
    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS)
    @java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD,
                                  java.lang.annotation.ElementType.METHOD,    
                                  java.lang.annotation.ElementType.PARAMETER,
                                  java.lang.annotation.ElementType.LOCAL_VARIABLE})
    public @interface Nullable 
    {
    }
    

    If you use the correct retention policy, then the annotations won't be available at runtime. From that point of view, it is just an internal thing.

    Even though this is not a strict science, I think it makes most sense to use an internal class for it.

    • It is an internal thing. (no functional or technical impact)
    • With many many many usages.
    • IDE's like IntelliJ support custom @Nullable/@NotNull annotations.
    • Most frameworks prefer to use their own internal version as well.

    Additional Questions (see comments):

    How to configure this in IntelliJ ?

    Click the "police officer" in the lower right corner of the IntelliJ status bar. And click "Configure inspections" in the popup. Next ...

提交回复
热议问题