简体   繁体   中英

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 line 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:

智能@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.

you can use .OrElse(). See this example

Optional<String> response = Optional.of("Not Null");
    Optional<String> response2 = Optional.empty();
    System.out.println(response.orElse(""));
    System.out.println(response2.orElse("Dont want to return null"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM