Preconditions.java revision ee2f7df9ee8a4f43c3b0858bad08a4f0a59a627f
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 17package 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 */ 23public 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 /** 71 * Check the requested flags, throwing if any requested flags are outside 72 * the allowed set. 73 */ 74 public static void checkFlagsArgument(int requestedFlags, int allowedFlags) { 75 if ((requestedFlags & allowedFlags) != requestedFlags) { 76 throw new IllegalArgumentException("Requested flags 0x" 77 + Integer.toHexString(requestedFlags) + ", but only 0x" 78 + Integer.toHexString(allowedFlags) + " are allowed"); 79 } 80 } 81} 82