Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to document that return value is not null with Java Optional?

Is it possible to document that return value is not null with Java Optional?

Most tools and frameworks care only about arguments but I'd like to express in type that return value is not null (instead of doing that in JavaDoc).

UPDATE Looks like you can agree with team to use Optional as return value if you want to express possible null and direct object when it is definitely not null:

public Optional<Job> getJob() {  ... }
public Job extractJob(NonNullJobHolder<Job> holder) { ... }
like image 268
gavenkoa Avatar asked Jun 23 '26 17:06

gavenkoa


1 Answers

I don't know why you're under the impression that most of them apply only to parameters.

org.eclipse.jdt.annotation.NonNull

@Documented
@Retention(value=CLASS)
@Target(value={FIELD,METHOD,PARAMETER,LOCAL_VARIABLE})
public @interface NonNull

org.jetbrains.annotations.NotNull

The @NotNull annotation is, actually, an explicit contract declaring that:

  • A method should not return null
  • Variables (fields, local variables, and parameters) cannot hold a null value

Usage:

intellij @NotNull

javax.validation.constraints.NotNull

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
@Retention(value=RUNTIME)
@Documented
@Constraint(validatedBy={})
public @interface NotNull

javax.annotation.Nonnull

@Documented
@TypeQualifier
@Retention(value=RUNTIME)
public @interface Nonnull

Usage:

javax @Nonnull


So feel free to use any one of these four on your method.

like image 107
Michael Avatar answered Jun 25 '26 07:06

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!