common: Add utility class for non-null things
[deliverable/tracecompass.git] / org.eclipse.tracecompass.common.core / src / org / eclipse / tracecompass / common / core / NonNullUtils.java
1 /*******************************************************************************
2 * Copyright (c) 2014 Ericsson
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Alexandre Montplaisir - Initial API and implementation
11 *******************************************************************************/
12
13 package org.eclipse.tracecompass.common.core;
14
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.Nullable;
17
18 /**
19 * Utility methods to handle {@link org.eclipse.jdt.annotation.NonNull}
20 * annotations.
21 *
22 * @author Alexandre Montplaisir
23 */
24 public final class NonNullUtils {
25
26 private NonNullUtils() {}
27
28 /**
29 * Convert a potentially null string into an empty one if it is null.
30 *
31 * @param str
32 * The string to null-check, and convert to an empty string if
33 * null.
34 * @return The non-null string
35 */
36 public static String nullToEmptyString(@Nullable String str) {
37 if (str == null) {
38 return ""; //$NON-NLS-1$
39 }
40 return str;
41 }
42
43 /**
44 * Convert a non-annotated object reference to a {@link NonNull} one.
45 *
46 * If the reference is actually null, a {@link NullPointerException} is
47 * thrown. This is usually more desirable than letting an unwanted null
48 * reference go through and fail much later.
49 *
50 * @param obj
51 * The object that is supposed to be non-null
52 * @return A {@link NonNull} reference to the same object
53 * @throws NullPointerException
54 * If the reference was actually null
55 */
56 public static <T> T checkNotNull(@Nullable T obj) {
57 if (obj == null) {
58 throw new NullPointerException();
59 }
60 return obj;
61 }
62 }
This page took 0.035421 seconds and 5 git commands to generate.