Class Preconditions


  • public final class Preconditions
    extends Object
    Collection of simple checks to be used to check for method invocation preconditions


    The default behavior for precondition checks provided by this class is to throw an APIPreconditionException in case the given arguments do not match the requirements. Some of the methods may support extended control over the actual type of exception that will be thrown by allowing the calling instance to provide it's onw runtime exception instance.


    Please note that this class should primarily be used for non-method parameter related precondition/object state checks as the default APIPreconditionException indicates that resolving the failed validation isn't necessarily within the responsibility of the calling instance (although it can be). A common precondition check would be for example to check whether the invoked object is in a proper state in order to process the invocation. If not, this may possibly be resolved by the calling instance by e.g. some additional object initialization. However, it may also prove to be unresolvable for example when the invoked method is only supported for certain object states. To verify the values of given method parameters use Parameters.

    • Method Detail

      • requires

        public static <T,X extends RuntimeException> void requires​(Predicate<T> condition,
                                                                   T value,
                                                                   X exception)
        Checks the condition and throws the given runtime exception in case the condition is not met.
        Type Parameters:
        T - the type of the value to check
        X - type of the runtime exception to be thrown
        Parameters:
        condition - The condition to check for
        value - The value to check against the condition
        exception - The exception to be thrown in case the condition is not met
      • requireNonNull

        public static void requireNonNull​(Object obj,
                                          String message)
        Checks that the given obj is not null. Otherwise an exception with the given error message will be thrown.
        Parameters:
        obj - The object to check
        message - Error message to be propagated to the exception in case of a failed validation
        Throws:
        APIPreconditionException - If the given obj is null
      • requireNonEmpty

        public static void requireNonEmpty​(String obj,
                                           String message)
        Checks that the given String is neither null nor empty. Otherwise an exception with the given error message will be thrown.
        Parameters:
        obj - The String to check
        message - Error message to be propagated to the exception in case of a failed validation
        Throws:
        APIPreconditionException - If the given String is either null or empty