A utility class to check arguments (preconditions) and state. Examples of use: public void setActionWithTimeout(Action action delegate, int timeout) { this.action = Require.nonNull("Action", action); this.timeout = Require.positive("Timeout", timeout); }
| 38 | * </pre> |
| 39 | */ |
| 40 | @NullMarked |
| 41 | public final class Require { |
| 42 | |
| 43 | private static final String MUST_BE_SET = "%s must be set"; |
| 44 | private static final String MUST_NOT_BE_SET = "%s must not be set"; |
| 45 | private static final String MUST_EXIST = "%s must exist: %s"; |
| 46 | private static final String MUST_BE_DIR = "%s must be a directory: %s"; |
| 47 | private static final String MUST_BE_FILE = "%s must be a regular file: %s"; |
| 48 | private static final String MUST_BE_EQUAL = "%s must be equal to `%s`"; |
| 49 | private static final String MUST_BE_EXECUTABLE = "%s must be executable: %s"; |
| 50 | private static final String MUST_BE_NON_NEGATIVE = "%s must be 0 or greater"; |
| 51 | private static final String MUST_BE_POSITIVE = "%s must be greater than 0"; |
| 52 | private static final String MUST_BE_BETWEEN = "%s must be between %s and %s (inclusive)"; |
| 53 | private static final String MUST_NOT_BE_EMPTY = "%s must not be empty"; |
| 54 | private static final String MUST_NOT_BE_BLANK = "%s must not be blank"; |
| 55 | |
| 56 | private Require() { |
| 57 | // An utility class |
| 58 | } |
| 59 | |
| 60 | public static void precondition(boolean condition, String message, Object... args) { |
| 61 | if (!condition) { |
| 62 | throw new IllegalArgumentException(String.format(message, args)); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public static <T> T nonNull(String argName, @Nullable T arg) { |
| 67 | if (arg == null) { |
| 68 | throw new IllegalArgumentException(String.format(MUST_BE_SET, argName)); |
| 69 | } |
| 70 | return arg; |
| 71 | } |
| 72 | |
| 73 | public static <T> T nonNull(String argName, @Nullable T arg, String message, Object... args) { |
| 74 | if (arg == null) { |
| 75 | throw new IllegalArgumentException(String.join(" ", argName, String.format(message, args))); |
| 76 | } |
| 77 | return arg; |
| 78 | } |
| 79 | |
| 80 | public static <T> void isNull(String argName, @Nullable T arg) { |
| 81 | if (arg != null) { |
| 82 | throw new IllegalArgumentException(String.format(MUST_NOT_BE_SET, argName)); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | public static <T> ArgumentChecker<T> argument(String argName, @Nullable T arg) { |
| 87 | return new ArgumentChecker<>(argName, arg); |
| 88 | } |
| 89 | |
| 90 | public static Duration nonNegative(String argName, @Nullable Duration arg) { |
| 91 | nonNull(argName, arg); |
| 92 | if (arg.isNegative()) { |
| 93 | throw new IllegalArgumentException(String.format(MUST_BE_NON_NEGATIVE, argName)); |
| 94 | } |
| 95 | return arg; |
| 96 | } |
| 97 |
nothing calls this directly
no outgoing calls
no test coverage detected