Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.internal.util;
     18 
     19 /**
     20  * Simple static methods to be called at the start of your own methods to verify
     21  * correct arguments and state.
     22  */
     23 public class Preconditions {
     24 
     25     /**
     26      * Ensures that an object reference passed as a parameter to the calling
     27      * method is not null.
     28      *
     29      * @param reference an object reference
     30      * @return the non-null reference that was validated
     31      * @throws NullPointerException if {@code reference} is null
     32      */
     33     public static <T> T checkNotNull(T reference) {
     34         if (reference == null) {
     35             throw new NullPointerException();
     36         }
     37         return reference;
     38     }
     39 
     40     /**
     41      * Ensures that an object reference passed as a parameter to the calling
     42      * method is not null.
     43      *
     44      * @param reference an object reference
     45      * @param errorMessage the exception message to use if the check fails; will
     46      *     be converted to a string using {@link String#valueOf(Object)}
     47      * @return the non-null reference that was validated
     48      * @throws NullPointerException if {@code reference} is null
     49      */
     50     public static <T> T checkNotNull(T reference, Object errorMessage) {
     51         if (reference == null) {
     52             throw new NullPointerException(String.valueOf(errorMessage));
     53         }
     54         return reference;
     55     }
     56 
     57     /**
     58      * Ensures the truth of an expression involving the state of the calling
     59      * instance, but not involving any parameters to the calling method.
     60      *
     61      * @param expression a boolean expression
     62      * @throws IllegalStateException if {@code expression} is false
     63      */
     64     public static void checkState(boolean expression) {
     65         if (!expression) {
     66             throw new IllegalStateException();
     67         }
     68     }
     69 }
     70