Class OptionalUtil

java.lang.Object
org.checkerframework.checker.optional.util.OptionalUtil

@AnnotatedFor("optional") public final class OptionalUtil extends Object
This is a utility class for the Optional Checker.

To avoid the need to write the OptionalUtil class name, do:

import static org.checkerframework.checker.optional.util.OptionalUtil.castPresent;
or
import static org.checkerframework.checker.optional.util.OptionalUtil.*;

Runtime Dependency: If you use this class, you must distribute (or link to) checker-qual.jar, along with your binaries. Or, you can copy this class into your own project.

  • Method Details

    • castPresent

      @EnsuresPresent("#1") public static <T extends @MaybePresent Object> @Present Optional<T> castPresent(@MaybePresent Optional<T> ref)
      A method that suppresses warnings from the Optional Checker.

      The method takes a possibly-empty Optional reference, unsafely casts it to have the @Present type qualifier, and returns it. The Optional Checker considers both the return value, and also the argument, to be present after the method call. Therefore, the castPresent method can be used either as a cast expression or as a statement.

      
         // one way to use as a cast:
        @Present String s = castPresent(possiblyEmpty1);
      
         // another way to use as a cast:
         castPresent(possiblyEmpty2).toString();
      
         // one way to use as a statement:
         castPresent(possiblyEmpty3);
         possiblyEmpty3.toString();
       
      The castPresent method is intended to be used in situations where the programmer definitively knows that a given Optional reference is present, but the type system is unable to make this deduction. It is not intended for defensive programming, in which a programmer cannot prove that the value is not empty but wishes to have an earlier indication if it is. See the Checker Framework Manual for further discussion.

      The method throws AssertionError if Java assertions are enabled and the argument is empty. If the exception is ever thrown, then that indicates that the programmer misused the method by using it in a circumstance where its argument can be empty.

      Type Parameters:
      T - the type of content of the Optional
      Parameters:
      ref - an Optional reference of @MaybePresent type, that is present at run time
      Returns:
      the argument, casted to have the type qualifier @Present