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) { ... }
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:
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:
So feel free to use any one of these four on your method.