7

My java method can return null and non null results. I want mark method with @Nullable annotation to make it more readable.

I used com.sun.istack.internal.Nullable but sonar says Classes from "sun.*" packages should not be used. Code smell Major squid:S1191.

I try to find more similar annotations, but there are variants from different IDE, not from java vendor.

Does java (oracle) provides alternatives for nullable annotation or I should use third party libraries only? If I have to use third party library to have an @Nullable which one should be good?

Sergii
  • 7,044
  • 14
  • 58
  • 116
  • 4
    Use `javax.annotation.Nullable` from [JSR 305](https://jcp.org/en/jsr/detail?id=305) instead of an internal Sun class. You can find that annotation in for example [com.google.code.findbugs:jsr305](http://search.maven.org/#artifactdetails%7Ccom.google.code.findbugs%7Cjsr305%7C3.0.2%7Cjar) – Jesper Jul 25 '17 at 09:25
  • 5
    you can just return `Optional` – dehasi Jul 25 '17 at 09:25
  • Relevant/Duplicate : [Can't find @Nullable inside javax.annotation.*](https://stackoverflow.com/questions/19030954/cant-find-nullable-inside-javax-annotation) – Aaron Jul 25 '17 at 09:25
  • 2
    i promote the comment from @dehasi. just return an optional, this is probably the most readable version – Lino Jul 25 '17 at 09:27
  • @Jesper - good idea thanks. – Sergii Jul 25 '17 at 09:37
  • @dehasi Like it. but the method is private, and it is called from lambda, the result is wrapped with optional – Sergii Jul 25 '17 at 09:38
  • Related: https://stackoverflow.com/questions/4963300/which-notnull-java-annotation-should-i-use – tkruse Dec 06 '18 at 01:23

4 Answers4

5

Well, I think for Sonar you could use edu.umd.cs.findbugs.annotations.*, which are deprecated and advise you to use javax.annotation.Nullable.

I mainly use the Jetbrains ones, https://www.jetbrains.com/help/idea/nullable-and-notnull-annotations.html, but my main goal is the analysis in IntelliJ.

David Vonka
  • 511
  • 4
  • 14
3

If you can, consider using Optional<T> as the return type to make it more readable. You can express optionality utilizing the type system and benefit from the rich monadic-like API instead of wondering which annotation is the right one.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
0

Optional<T> or @Nullable or @return tag from java-doc are ways to say to users of your API that a method can return null. But you mentioned in comments that your method is private. It means that nobody, except you, can use it. That's why no additional stuff needed.

dehasi
  • 2,644
  • 1
  • 19
  • 31
0

With FIndbugs/Spotbugs, use @CheckForNull. See https://sourceforge.net/p/findbugs/bugs/1181)

tkruse
  • 10,222
  • 7
  • 53
  • 80