Class Preconditions


  • @GwtCompatible
    public final class Preconditions
    extends java.lang.Object
    Static convenience methods that help a method or constructor check whether it was invoked correctly (whether its preconditions have been met). These methods generally accept a boolean expression which is expected to be true (or in the case of checkNotNull, an object reference which is expected to be non-null). When false (or null) is passed instead, the Preconditions method throws an unchecked exception, which helps the calling method communicate to its caller that that caller has made a mistake. Example:
        
    
       /**
        * Returns the positive square root of the given value.
        *
        * @throws IllegalArgumentException if the value is negative
        */
       public static double sqrt(double value) {
         Preconditions.checkArgument(value >= 0.0, "negative value: %s", value);
         // calculate the square root
       }
    
       void exampleBadCaller() {
         double d = sqrt(-1.0);
       }
     
    In this example, checkArgument throws an IllegalArgumentException to indicate that exampleBadCaller made an error in its call to sqrt.

    Warning about performance

    The goal of this class is to improve readability of code, but in some circumstances this may come at a significant performance cost. Remember that parameter values for message construction must all be computed eagerly, and autoboxing and varargs array creation may happen as well, even when the precondition check then succeeds (as it should almost always do in production). In some circumstances these wasted CPU cycles and allocations can add up to a real problem. Performance-sensitive precondition checks can always be converted to the customary form:

        
    
       if (value < 0.0) {
         throw new IllegalArgumentException("negative value: " + value);
       }
     

    Other types of preconditions

    Not every type of precondition failure is supported by these methods. Continue to throw standard JDK exceptions such as NoSuchElementException or UnsupportedOperationException in the situations they are intended for.

    Non-preconditions

    It is of course possible to use the methods of this class to check for invalid conditions which are not the caller's fault. Doing so is not recommended because it is misleading to future readers of the code and of stack traces. See Conditional failures explained in the Guava User Guide for more advice.

    java.util.Objects.requireNonNull()

    Projects which use com.google.common should generally avoid the use of Objects.requireNonNull(Object). Instead, use whichever of checkNotNull(Object) or Verify.verifyNotNull(Object) is appropriate to the situation. (The same goes for the message-accepting overloads.)

    Only %s is supported

    In Preconditions error message template strings, only the "%s" specifier is supported, not the full range of Formatter specifiers. However, note that if the number of arguments does not match the number of occurrences of "%s" in the format string, Preconditions will still behave as expected, and will still include all argument values in the error message; the message will simply not be formatted exactly as intended.

    More information

    See the Guava User Guide on using Preconditions.

    Since:
    2.0 (imported from Google Collections Library)
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void checkArgument​(boolean expression)
      Ensures the truth of an expression involving one or more parameters to the calling method.
      static void checkArgument​(boolean expression, java.lang.Object errorMessage)
      Ensures the truth of an expression involving one or more parameters to the calling method.
      static void checkArgument​(boolean expression, java.lang.String errorMessageTemplate, java.lang.Object... errorMessageArgs)
      Ensures the truth of an expression involving one or more parameters to the calling method.
      static int checkElementIndex​(int index, int size)
      Ensures that index specifies a valid element in an array, list or string of size size.
      static int checkElementIndex​(int index, int size, java.lang.String desc)
      Ensures that index specifies a valid element in an array, list or string of size size.
      static <T> T checkNotNull​(T reference)
      Ensures that an object reference passed as a parameter to the calling method is not null.
      static <T> T checkNotNull​(T reference, java.lang.Object errorMessage)
      Ensures that an object reference passed as a parameter to the calling method is not null.
      static <T> T checkNotNull​(T reference, java.lang.String errorMessageTemplate, java.lang.Object... errorMessageArgs)
      Ensures that an object reference passed as a parameter to the calling method is not null.
      static int checkPositionIndex​(int index, int size)
      Ensures that index specifies a valid position in an array, list or string of size size.
      static int checkPositionIndex​(int index, int size, java.lang.String desc)
      Ensures that index specifies a valid position in an array, list or string of size size.
      static void checkPositionIndexes​(int start, int end, int size)
      Ensures that start and end specify a valid positions in an array, list or string of size size, and are in order.
      static void checkState​(boolean expression)
      Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
      static void checkState​(boolean expression, java.lang.Object errorMessage)
      Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
      static void checkState​(boolean expression, java.lang.String errorMessageTemplate, java.lang.Object... errorMessageArgs)
      Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • checkArgument

        public static void checkArgument​(boolean expression)
        Ensures the truth of an expression involving one or more parameters to the calling method.
        Parameters:
        expression - a boolean expression
        Throws:
        java.lang.IllegalArgumentException - if expression is false
      • checkArgument

        public static void checkArgument​(boolean expression,
                                         @Nullable
                                         java.lang.Object errorMessage)
        Ensures the truth of an expression involving one or more parameters to the calling method.
        Parameters:
        expression - a boolean expression
        errorMessage - the exception message to use if the check fails; will be converted to a string using String.valueOf(Object)
        Throws:
        java.lang.IllegalArgumentException - if expression is false
      • checkArgument

        public static void checkArgument​(boolean expression,
                                         @Nullable
                                         java.lang.String errorMessageTemplate,
                                         @Nullable
                                         java.lang.Object... errorMessageArgs)
        Ensures the truth of an expression involving one or more parameters to the calling method.
        Parameters:
        expression - a boolean expression
        errorMessageTemplate - a template for the exception message should the check fail. The message is formed by replacing each %s placeholder in the template with an argument. These are matched by position - the first %s gets errorMessageArgs[0] , etc. Unmatched arguments will be appended to the formatted message in square braces. Unmatched placeholders will be left as-is.
        errorMessageArgs - the arguments to be substituted into the message template. Arguments are converted to strings using String.valueOf(Object).
        Throws:
        java.lang.IllegalArgumentException - if expression is false
        java.lang.NullPointerException - if the check fails and either errorMessageTemplate or errorMessageArgs is null (don't let this happen)
      • checkState

        public static void checkState​(boolean expression)
        Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
        Parameters:
        expression - a boolean expression
        Throws:
        java.lang.IllegalStateException - if expression is false
      • checkState

        public static void checkState​(boolean expression,
                                      @Nullable
                                      java.lang.Object errorMessage)
        Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
        Parameters:
        expression - a boolean expression
        errorMessage - the exception message to use if the check fails; will be converted to a string using String.valueOf(Object)
        Throws:
        java.lang.IllegalStateException - if expression is false
      • checkState

        public static void checkState​(boolean expression,
                                      @Nullable
                                      java.lang.String errorMessageTemplate,
                                      @Nullable
                                      java.lang.Object... errorMessageArgs)
        Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
        Parameters:
        expression - a boolean expression
        errorMessageTemplate - a template for the exception message should the check fail. The message is formed by replacing each %s placeholder in the template with an argument. These are matched by position - the first %s gets errorMessageArgs[0] , etc. Unmatched arguments will be appended to the formatted message in square braces. Unmatched placeholders will be left as-is.
        errorMessageArgs - the arguments to be substituted into the message template. Arguments are converted to strings using String.valueOf(Object).
        Throws:
        java.lang.IllegalStateException - if expression is false
        java.lang.NullPointerException - if the check fails and either errorMessageTemplate or errorMessageArgs is null (don't let this happen)
      • checkNotNull

        public static <T> T checkNotNull​(T reference)
        Ensures that an object reference passed as a parameter to the calling method is not null.
        Parameters:
        reference - an object reference
        Returns:
        the non-null reference that was validated
        Throws:
        java.lang.NullPointerException - if reference is null
      • checkNotNull

        public static <T> T checkNotNull​(T reference,
                                         @Nullable
                                         java.lang.Object errorMessage)
        Ensures that an object reference passed as a parameter to the calling method is not null.
        Parameters:
        reference - an object reference
        errorMessage - the exception message to use if the check fails; will be converted to a string using String.valueOf(Object)
        Returns:
        the non-null reference that was validated
        Throws:
        java.lang.NullPointerException - if reference is null
      • checkNotNull

        public static <T> T checkNotNull​(T reference,
                                         @Nullable
                                         java.lang.String errorMessageTemplate,
                                         @Nullable
                                         java.lang.Object... errorMessageArgs)
        Ensures that an object reference passed as a parameter to the calling method is not null.
        Parameters:
        reference - an object reference
        errorMessageTemplate - a template for the exception message should the check fail. The message is formed by replacing each %s placeholder in the template with an argument. These are matched by position - the first %s gets errorMessageArgs[0] , etc. Unmatched arguments will be appended to the formatted message in square braces. Unmatched placeholders will be left as-is.
        errorMessageArgs - the arguments to be substituted into the message template. Arguments are converted to strings using String.valueOf(Object).
        Returns:
        the non-null reference that was validated
        Throws:
        java.lang.NullPointerException - if reference is null
      • checkElementIndex

        public static int checkElementIndex​(int index,
                                            int size)
        Ensures that index specifies a valid element in an array, list or string of size size. An element index may range from zero, inclusive, to size, exclusive.
        Parameters:
        index - a user-supplied index identifying an element of an array, list or string
        size - the size of that array, list or string
        Returns:
        the value of index
        Throws:
        java.lang.IndexOutOfBoundsException - if index is negative or is not less than size
        java.lang.IllegalArgumentException - if size is negative
      • checkElementIndex

        public static int checkElementIndex​(int index,
                                            int size,
                                            @Nullable
                                            java.lang.String desc)
        Ensures that index specifies a valid element in an array, list or string of size size. An element index may range from zero, inclusive, to size, exclusive.
        Parameters:
        index - a user-supplied index identifying an element of an array, list or string
        size - the size of that array, list or string
        desc - the text to use to describe this index in an error message
        Returns:
        the value of index
        Throws:
        java.lang.IndexOutOfBoundsException - if index is negative or is not less than size
        java.lang.IllegalArgumentException - if size is negative
      • checkPositionIndex

        public static int checkPositionIndex​(int index,
                                             int size)
        Ensures that index specifies a valid position in an array, list or string of size size. A position index may range from zero to size, inclusive.
        Parameters:
        index - a user-supplied index identifying a position in an array, list or string
        size - the size of that array, list or string
        Returns:
        the value of index
        Throws:
        java.lang.IndexOutOfBoundsException - if index is negative or is greater than size
        java.lang.IllegalArgumentException - if size is negative
      • checkPositionIndex

        public static int checkPositionIndex​(int index,
                                             int size,
                                             @Nullable
                                             java.lang.String desc)
        Ensures that index specifies a valid position in an array, list or string of size size. A position index may range from zero to size, inclusive.
        Parameters:
        index - a user-supplied index identifying a position in an array, list or string
        size - the size of that array, list or string
        desc - the text to use to describe this index in an error message
        Returns:
        the value of index
        Throws:
        java.lang.IndexOutOfBoundsException - if index is negative or is greater than size
        java.lang.IllegalArgumentException - if size is negative
      • checkPositionIndexes

        public static void checkPositionIndexes​(int start,
                                                int end,
                                                int size)
        Ensures that start and end specify a valid positions in an array, list or string of size size, and are in order. A position index may range from zero to size, inclusive.
        Parameters:
        start - a user-supplied index identifying a starting position in an array, list or string
        end - a user-supplied index identifying a ending position in an array, list or string
        size - the size of that array, list or string
        Throws:
        java.lang.IndexOutOfBoundsException - if either index is negative or is greater than size, or if end is less than start
        java.lang.IllegalArgumentException - if size is negative