1 /* 2 * Copyright 2014 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 android.hardware.camera2.cts.helpers; 18 19 import java.io.Closeable; 20 import java.io.IOException; 21 22 /** 23 * Helper set of methods for dealing with objects that are sometimes {@code null}. 24 * 25 * <p>Used to remove common patterns like: <pre>{@code 26 * if (obj != null) { 27 * obj.doSomething(); 28 * }</pre> 29 * 30 * If this is common, consider adding {@code doSomething} to this class so that the code 31 * looks more like <pre>{@code 32 * MaybeNull.doSomething(obj); 33 * }</pre> 34 */ 35 public class MaybeNull { 36 /** 37 * Close the underlying {@link AutoCloseable}, if it's not {@code null}. 38 * 39 * @param closeable An object which implements {@link AutoCloseable}. 40 * @throws Exception If {@link AutoCloseable#close} fails. 41 */ 42 public static <T extends AutoCloseable> void close(T closeable) throws Exception { 43 if (closeable != null) { 44 closeable.close(); 45 } 46 } 47 48 /** 49 * Close the underlying {@link UncheckedCloseable}, if it's not {@code null}. 50 * 51 * <p>No checked exceptions are thrown. An unknown runtime exception might still 52 * be raised.</p> 53 * 54 * @param closeable An object which implements {@link UncheckedCloseable}. 55 */ 56 public static <T extends UncheckedCloseable> void close(T closeable) { 57 if (closeable != null) { 58 closeable.close(); 59 } 60 } 61 62 /** 63 * Close the underlying {@link Closeable}, if it's not {@code null}. 64 * 65 * @param closeable An object which implements {@link Closeable}. 66 * @throws Exception If {@link Closeable#close} fails. 67 */ 68 public static <T extends Closeable> void close(T closeable) throws IOException { 69 if (closeable != null) { 70 closeable.close(); 71 } 72 } 73 74 // Suppress default constructor for noninstantiability 75 private MaybeNull() { throw new AssertionError(); } 76 } 77