1 package com.atlassian.user.util;
2
3 public class Assert
4 {
5 /**
6 * Throws an IllegalArgumentException with a given message when an assertion fails.
7 *
8 * @param message the message to use in the IllegalArgumentException
9 */
10 private static void fail(String message)
11 {
12 throw new IllegalArgumentException(message);
13 }
14
15 /**
16 * Assert that an object is not <tt>null</tt>, throwing IllegalArgumentException if it is.
17 *
18 * @param object the object to check for null
19 * @param message the exception message to use if the assertion fails
20 * @throws IllegalArgumentException if the object is null
21 */
22 public static <T> T notNull(T object, String message)
23 {
24 if (object == null)
25 fail(message);
26 return object;
27 }
28
29 /**
30 * Asserts that an expression is true, throwing an IllegalArgumentException if it is false.
31 *
32 * @param expression the expression to check
33 * @param message the exception message to use if the assertion fails
34 * @throws IllegalArgumentException if the assertion fails
35 */
36 public static void isTrue(boolean expression, String message)
37 {
38 if (!expression)
39 fail(message);
40 }
41
42 /**
43 * Assert that the provided object is an instance of the provided class, throwing an IllegalArgumentException if is it not.
44 *
45 * @param clazz the required class
46 * @param object the object to check
47 * @throws IllegalArgumentException if the object is not an instance of clazz
48 */
49 public static <T> T isInstanceOf(Class<T> clazz, Object object)
50 {
51 if (!clazz.isInstance(object))
52 fail(object + " must be an instance of " + clazz);
53 return clazz.cast(object);
54 }
55
56 /**
57 * Assert that the provided object is an instance of the provided class, throwing an IllegalArgumentException if is it not.
58 *
59 * @param clazz the required class
60 * @param object the object to check
61 * @param message the exception message to use if the assertion fails
62 * @throws IllegalArgumentException if the object is not an instance of clazz
63 */
64 public static <T> T isInstanceOf(Class<T> clazz, Object object, String message)
65 {
66 if (!clazz.isInstance(object))
67 fail(message);
68 return clazz.cast(object);
69 }
70 }