Debian Codegraph @

org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/Checks.java

raw symbols SCIP
1 /*******************************************************************************
2 * Copyright (c) 2016, 2019 Stephan Herrmann and others.
3 *
4 * This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License 2.0
6 * which accompanies this distribution, and is available at
7 * https://www.eclipse.org/legal/epl-2.0/
8 *
9 * SPDX-License-Identifier: EPL-2.0
10 *
11 * Contributors:
12 * Stephan Herrmann - initial API and implementation
13 *******************************************************************************/
14 package org.eclipse.jdt.annotation;
15
16 import java.util.Collection;
17 import java.util.Optional;
18 import java.util.function.Consumer;
19 import java.util.function.Function;
20 import java.util.function.Supplier;
21
22 /**
23 * Utility functions intended for use with the null annotations defined in this package.
24 *
25 * <p>
26 * For maximum generality, all type parameters of methods in this class are not constraint
27 * to either non-null nor nullable. Users of these methods can freely choose these types.
28 * </p>
29 * <p>
30 * Methods in this class come in three groups: Assertions, Requirements, as well as Queries, conversions and computations.
31 * </p>
32 *
33 * <h2>Assertions</h2>
34 * <p>
35 * All methods in this group start with the prefix "assert", and work similar to the <code>assert</code> keyword.
36 * </p>
37 * <ul>
38 * <li>One or more values are checked for <code>null</code>.</li>
39 * <li>If any value is <code>null</code>, an exception is thrown.</li>
40 * <li>The method has no other effect (except for potential side effects in an Iterator).</li>
41 * </ul>
42 *
43 * <h2>Requirements</h2>
44 * <p>
45 * All methods in this group start with the prefix "require". They encode domain knowledge of the developer
46 * and make this knowledge visible to static null analysis.
47 * </p>
48 * <ul>
49 * <li>One or more values are checked for <code>null</code>.</li>
50 * <li>If any value is <code>null</code>, an exception is thrown.</li>
51 * <li>Otherwise a guaranteed non-null value is returned.</li>
52 * </ul>
53 * <p>For Strings and Collections additional checks for empty may be included.</p>
54 * <p>
55 * Typical usage includes the case of interfacing with legacy API, that is not specified using
56 * null annotations, but where corresponding guarantees are given informally:
57 * </p>
58 * <pre>
59 * interface LegacyThing {
60 * {@literal /}** @return the name of this thing, never &lt;code&gt;null&lt;/code&gt;. *{@literal /}
61 * String getName();
62 * }
63 * ...
64 * public void process(@NonNull LegacyThing t) {
65 * {@literal @}NonNull String name = Checks.requireNonNull(t.getName(), "LegacyThing is supposed to have a name");
66 * ...
67 * }
68 * </pre>
69 *
70 * <h2>Queries, conversions and computations</h2>
71 * <p>
72 * A commonality among methods in this group is the null-safety that can be verified by static null analysis,
73 * hence in a fully analyzed program none of these methods should throw an exception.
74 * </p>
75 * <dl>
76 * <dt>boolean queries</dt>
77 * <dd>Methods {@link #isNull(Object)}, {@link #isAnyNull(Object...)}, {@link #containsNull(Iterable)} simply
78 * answer whether a null value could be found in the argument(s).</dd>
79 * <dt>conversions</dt>
80 * <dd>Methods {@link #nonNullElse(Object, Object)}, {@link #nonNullElseGet(Object, Supplier)}, {@link #asNullable(Optional)}
81 * and the {@link #unboxElse(Boolean, boolean)} family of methods provide null-safe conversions,
82 * which can be checked by static analysis.</dd>
83 * <dt>computations</dt>
84 * <dd>Methods {@link #ifNonNull(Object, Consumer)}, {@link #applyIfNonNull(Object, Function)},
85 * {@link #applyIfNonNullElse(Object, Function, Object)} and {@link #applyIfNonNullElseGet(Object, Function, Supplier)}
86 * feed unsafe values into a given functional expression in a null-safe way.</dd>
87 * </dl>
88 *
89 * @since 2.1
90 */
91 public class Checks {
92
93 /**
94 * Checks whether any of the provided values is <code>null</code>.
95 * @param values arbitrary values to be checked
96 * @throws NullPointerException if a <code>null</code> was found among values.
97 */
98 @SafeVarargs
99 public static <T> void assertNonNull(T @NonNull... values) {
100 for (int i = 0; i < values.length; i++) {
101 if (values[i] == null)
102 throw new NullPointerException("Value in position "+i+" must not be null"); //$NON-NLS-1$//$NON-NLS-2$
103 }
104 }
105
106 /**
107 * Checks whether any of the provided values is <code>null</code>.
108 * @param message explanatory message to be used when throwing {@link NullPointerException}.
109 * @param values arbitrary values to be checked
110 * @throws NullPointerException if a <code>null</code> was found among values.
111 */
112 @SafeVarargs
113 public static <T> void assertNonNullWithMessage(String message, T @NonNull... values) {
114 for (T v : values)
115 if (v == null)
116 throw new NullPointerException(message);
117 }
118
119 /**
120 * Checks whether any element in the provided values is <code>null</code>.
121 * @param values an Iterable of arbitrary values to be checked
122 * @throws NullPointerException if a <code>null</code> was found among the elements in values.
123 */
124 public static <T> void assertNonNullElements(@NonNull Iterable<T> values) {
125 int count = 0;
126 for (T v : values) {
127 if (v == null)
128 throw new NullPointerException("Value in position "+count+" must not be null"); //$NON-NLS-1$ //$NON-NLS-2$
129 count++;
130 }
131 }
132
133 /**
134 * Checks whether any of the provided values is <code>null</code>.
135 * @param values an iterable of arbitrary values to be checked
136 * @param message explanatory message to be used when throwing {@link NullPointerException}.
137 * @throws NullPointerException if a <code>null</code> was found among the elements in values.
138 */
139 public static <T> void assertNonNullElements(@NonNull Iterable<T> values, String message) {
140 for (T v : values)
141 if (v == null)
142 throw new NullPointerException(message);
143 }
144
145 /**
146 * Answer the given value as a non-null value.
147 * Throws {@link NullPointerException} if the given value was <code>null</code>.
148 *
149 * @param value an arbitrary value, maybe <code>null</code>.
150 * @return the original passed value, guaranteed not to be <code>null</code>.
151 *
152 * @throws NullPointerException if the given value was <code>null</code>.
153 */
154 public static <T> @NonNull T requireNonNull(@Nullable T value) {
155 if (value == null)
156 throw new NullPointerException();
157 return value;
158 }
159
160 /**
161 * Answer the given value as a non-null value.
162 * Throws {@link NullPointerException} if the given value was <code>null</code>.
163 *
164 * @param value an arbitrary value, maybe <code>null</code>.
165 * @param message explanatory message to be used when throwing {@link NullPointerException}.
166 * @return the original passed value, guaranteed not to be <code>null</code>.
167 *
168 * @throws NullPointerException if the given value was <code>null</code>.
169 */
170 public static <T> @NonNull T requireNonNull(@Nullable T value, @NonNull String message) {
171 if (value == null)
172 throw new NullPointerException(message);
173 return value;
174 }
175
176 /**
177 * Answer the given value, guaranteeing it to be neither <code>null</code> nor
178 * an empty string.
179 *
180 * @param value value to be checked
181 * @return the given value, guaranteed to be neither <code>null</code> nor
182 * and empty string.
183 *
184 * @throws NullPointerException if the given value was <code>null</code>
185 * @throws IllegalArgumentException if the given value was an empty string.
186 */
187 public static @NonNull String requireNonEmpty(@Nullable String value) {
188 if (value == null)
189 throw new NullPointerException();
190 if (value.isEmpty())
191 throw new IllegalArgumentException();
192 return value;
193 }
194
195 /**
196 * Answer the given value, guaranteeing it to be neither <code>null</code> nor
197 * an empty string.
198 *
199 * @param value value to be checked
200 * @param message explanatory message to be used when throwing an exception.
201 * @return the given value, guaranteed to be neither <code>null</code> nor
202 * an empty string.
203 *
204 * @throws NullPointerException if the given value was <code>null</code>
205 * @throws IllegalArgumentException if the given value was an empty string.
206 */
207 public static @NonNull String requireNonEmpty(@Nullable String value, String message) {
208 if (value == null)
209 throw new NullPointerException(message);
210 if (value.isEmpty())
211 throw new IllegalArgumentException(message);
212 return value;
213 }
214
215 /**
216 * Answer the given value, guaranteeing it to be neither <code>null</code> nor
217 * an empty collection. This method doesn't make any statement about whether
218 * or not elements in the collection can possibly be <code>null</code>.
219 *
220 * @param value value to be checked
221 * @return the given value, guaranteed to be neither <code>null</code> nor
222 * an empty collection.
223 *
224 * @throws NullPointerException if the given value was <code>null</code>
225 * @throws IllegalArgumentException if the given value was an empty collection.
226 */
227 public static <C extends Collection<?>> @NonNull C requireNonEmpty(@Nullable C value) {
228 if (value == null)
229 throw new NullPointerException();
230 if (value.isEmpty())
231 throw new IllegalArgumentException();
232 return value;
233 }
234
235 /**
236 * Answer the given value, guaranteeing it to be neither <code>null</code> nor
237 * an empty collection. This method doesn't make any statement about whether
238 * or not elements in the collection can possibly be <code>null</code>.
239 *
240 * @param value value to be checked
241 * @param message explanatory message to be used when throwing an exception.
242 * @return the given value, guaranteed to be neither <code>null</code> nor
243 * an empty collection.
244 *
245 * @throws NullPointerException if the given value was <code>null</code>
246 * @throws IllegalArgumentException if the given value was an empty collection.
247 */
248 public static <C extends Collection<?>> @NonNull C requireNonEmpty(@Nullable C value, String message) {
249 if (value == null)
250 throw new NullPointerException(message);
251 if (value.isEmpty())
252 throw new IllegalArgumentException(message);
253 return value;
254 }
255
256 /**
257 * Answer whether the given value is <code>null</code>.
258 * Calling this method should express that a null check is performed
259 * which the compiler would normally deem unnecessary or redundant.
260 * By calling this method, these warnings will be avoided, and readers
261 * of that code will be informed that the check is redundant with respect
262 * to null analysis, and done only as a measure for extra safety.
263 * @param value an object which analysis at the call-site considers as non-null
264 * @return true if the argument is <code>null</code>, else false.
265 */
266 @SuppressWarnings("null") // intentionally performing a redundant check
267 public static boolean isNull(@NonNull Object value) { return value == null; }
268
269 /**
270 * Answer whether any of the given values is <code>null</code>.
271 * Depending on the nullness of concrete types for <code>T</code>,
272 * this method may or may not be redundant from the point of view of
273 * static analysis.
274 * @param values arbitrary values to be checked
275 * @return true if the argument is <code>null</code>, else false.
276 */
277 @SafeVarargs
278 public static <T> boolean isAnyNull(T @NonNull... values) {
279 for (int i = 0; i < values.length; i++) {
280 if (values[i] == null)
281 return true;
282 }
283 return false;
284 }
285
286 /**
287 * Answer whether an element in the provided values is <code>null</code>.
288 * Depending on the nullness of the given <code>Iterable</code>'s type argument,
289 * this method may or may not be redundant from the point of view of
290 * static analysis.
291 * @param values an iterable of arbitrary values
292 * @return true if the argument contains the value <code>null</code>, else false.
293 */
294 public static boolean containsNull(@NonNull Iterable<?> values) {
295 for (Object value : values) {
296 if (value == null)
297 return true;
298 }
299 return false;
300 }
301
302 /**
303 * Answer the value of an {@link Optional}, or <code>null</code> if it has no value.
304 *
305 * @param optional wrapper for an optional value
306 * @return the value or <code>null</code>.
307 */
308 public static <T> @Nullable T asNullable(@NonNull Optional<T> optional) {
309 if (optional.isPresent())
310 return optional.get();
311 return null;
312 }
313
314 /**
315 * Answer the given value as a non-null value.
316 * If the value was actually <code>null</code> the alternative 'fallbackValue' is returned.
317 *
318 * @param value an arbitrary value, maybe <code>null</code>.
319 * @param fallbackValue value to be returned when the value is <code>null</code>.
320 *
321 * @return the original passed value, guaranteed not to be <code>null</code>, or the fallback value.
322 */
323 public static <T> @NonNull T nonNullElse(@Nullable T value, @NonNull T fallbackValue) {
324 if (value == null)
325 return fallbackValue;
326 return value;
327 }
328
329 /**
330 * Answer the given value as a non-null value.
331 * If the value was actually <code>null</code> an alternative is computed by
332 * invoking the given 'fallbackSupplier'.
333 *
334 * @param value an arbitrary value, maybe <code>null</code>.
335 * @param fallbackSupplier will compute the value to be returned when the 'value' is <code>null</code>.
336 *
337 * @return the original passed value, guaranteed not to be <code>null</code>,
338 * or a fallback value provided by the 'fallbackSupplier'.
339 */
340 public static <T> @NonNull T nonNullElseGet(@Nullable T value, @NonNull Supplier<? extends @NonNull T> fallbackSupplier) {
341 if (value == null)
342 return fallbackSupplier.get();
343 return value;
344 }
345
346 /**
347 * Invoke the given consumer if and only if the given value is not <code>null</code>.
348 * Otherwise do nothing.
349 * @param value the value to be checked for null and possibly passed into the consumer.
350 * @param consumer the consumer to invoke after checking the value for null.
351 */
352 public static <T> void ifNonNull(@Nullable T value, @NonNull Consumer<@NonNull ? super T> consumer) {
353 if (value != null)
354 consumer.accept(value);
355 }
356
357 /**
358 * Apply the given function if and only if the given value is not <code>null</code>.
359 * @param value the value to be checked for <code>null</code> and possibly passed into the function.
360 * @param function the function to apply after checking the value for <code>null</code>.
361 * @return the result of applying 'function' with 'value',
362 * or <code>null</code> if 'value' was <code>null</code>
363 */
364 public static <T, U> @Nullable U applyIfNonNull(@Nullable T value, @NonNull Function<@NonNull ? super T, ? extends U> function) {
365 if (value != null)
366 return function.apply(value);
367 return null;
368 }
369
370 /**
371 * Apply the given function if and only if the given value is not <code>null</code>.
372 * @param value the value to be checked for <code>null</code> and possibly passed into the function.
373 * @param function the function to apply after checking the value for <code>null</code>.
374 * @param fallbackValue value to be returned when the 'value' is <code>null</code>.
375 * @return the result of applying 'function' with 'value',
376 * or the 'fallbackValue' if 'value' was <code>null</code>
377 */
378 public static <T, U> U applyIfNonNullElse(@Nullable T value, @NonNull Function<@NonNull ? super T, ? extends U> function, U fallbackValue) {
379 if (value != null)
380 return function.apply(value);
381 return fallbackValue;
382 }
383
384 /**
385 * Apply the given function if and only if the given value is not <code>null</code>.
386 * @param value the value to be checked for <code>null</code> and possibly passed into the function.
387 * @param function the function to apply after checking the value for <code>null</code>.
388 * @return the result of applying 'function' with 'value',
389 * or a value provided by invoking 'fallbackSupplier' if 'value' was <code>null</code>
390 */
391 public static <T, U> U applyIfNonNullElseGet(@Nullable T value, @NonNull Function<@NonNull ? super T, ? extends U> function,
392 @NonNull Supplier<? extends U> fallbackSupplier)
393 {
394 if (value != null)
395 return function.apply(value);
396 return fallbackSupplier.get();
397 }
398
399 /**
400 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
401 * Otherwise the given 'fallbackValue' is returned.
402 * @param boxedValue value, can be <code>null</code>.
403 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
404 * @return either the unboxed boolean corresponding to 'boxedValue' or
405 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
406 */
407 public static boolean unboxElse(@Nullable Boolean boxedValue, boolean fallbackValue) {
408 if (boxedValue == null)
409 return fallbackValue;
410 return boxedValue.booleanValue();
411 }
412
413 /**
414 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
415 * Otherwise the given 'fallbackValue' is returned.
416 * @param boxedValue value, can be <code>null</code>.
417 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
418 * @return either the unboxed byte corresponding to 'boxedValue' or
419 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
420 */
421 public static byte unboxElse(@Nullable Byte boxedValue, byte fallbackValue) {
422 if (boxedValue == null)
423 return fallbackValue;
424 return boxedValue.byteValue();
425 }
426
427 /**
428 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
429 * Otherwise the given 'fallbackValue' is returned.
430 * @param boxedValue value, can be <code>null</code>.
431 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
432 * @return either the unboxed char corresponding to 'boxedValue' or
433 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
434 */
435 public static char unboxElse(@Nullable Character boxedValue, char fallbackValue) {
436 if (boxedValue == null)
437 return fallbackValue;
438 return boxedValue.charValue();
439 }
440
441 /**
442 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
443 * Otherwise the given 'fallbackValue' is returned.
444 * @param boxedValue value, can be <code>null</code>.
445 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
446 * @return either the unboxed int corresponding to 'boxedValue' or
447 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
448 */
449 public static int unboxElse(@Nullable Integer boxedValue, int fallbackValue) {
450 if (boxedValue == null)
451 return fallbackValue;
452 return boxedValue.intValue();
453 }
454
455 /**
456 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
457 * Otherwise the given 'fallbackValue' is returned.
458 * @param boxedValue value, can be <code>null</code>.
459 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
460 * @return either the unboxed long corresponding to 'boxedValue' or
461 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
462 */
463 public static long unboxElse(@Nullable Long boxedValue, long fallbackValue) {
464 if (boxedValue == null)
465 return fallbackValue;
466 return boxedValue.longValue();
467 }
468
469 /**
470 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
471 * Otherwise the given 'fallbackValue' is returned.
472 * @param boxedValue value, can be <code>null</code>.
473 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
474 * @return either the unboxed short corresponding to 'boxedValue' or
475 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
476 */
477 public static short unboxElse(@Nullable Short boxedValue, short fallbackValue) {
478 if (boxedValue == null)
479 return fallbackValue;
480 return boxedValue.shortValue();
481 }
482
483 /**
484 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
485 * Otherwise the given 'fallbackValue' is returned.
486 * @param boxedValue value, can be <code>null</code>.
487 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
488 * @return either the unboxed float corresponding to 'boxedValue' or
489 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
490 */
491 public static float unboxElse(@Nullable Float boxedValue, float fallbackValue) {
492 if (boxedValue == null)
493 return fallbackValue;
494 return boxedValue.floatValue();
495 }
496
497 /**
498 * Unbox the given 'boxedValue' if and only if it is not <code>null</code>.
499 * Otherwise the given 'fallbackValue' is returned.
500 * @param boxedValue value, can be <code>null</code>.
501 * @param fallbackValue the value to use if 'boxedValue' is <code>null</code>
502 * @return either the unboxed double corresponding to 'boxedValue' or
503 * 'fallbackValue' if 'boxedValue' was <code>null</code>.
504 */
505 public static double unboxElse(@Nullable Double boxedValue, double fallbackValue) {
506 if (boxedValue == null)
507 return fallbackValue;
508 return boxedValue.doubleValue();
509 }
510 }