001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import java.text.MessageFormat; 005import java.util.function.Supplier; 006 007/** 008 * This utility class provides a collection of static helper methods for checking 009 * parameters at run-time. 010 * @since 2711 011 */ 012public final class CheckParameterUtil { 013 014 private CheckParameterUtil() { 015 // Hide default constructor for utils classes 016 } 017 018 /** 019 * Ensures a parameter is not {@code null} 020 * @param value The parameter to check 021 * @param parameterName The parameter name 022 * @throws IllegalArgumentException if the parameter is {@code null} 023 */ 024 public static void ensureParameterNotNull(Object value, String parameterName) { 025 if (value == null) 026 throw new IllegalArgumentException(MessageFormat.format("Parameter ''{0}'' must not be null", parameterName)); 027 } 028 029 /** 030 * Ensures a parameter is not {@code null}. Can find line number in the stack trace, so parameter name is optional 031 * @param value The parameter to check 032 * @throws IllegalArgumentException if the parameter is {@code null} 033 * @since 3871 034 */ 035 public static void ensureParameterNotNull(Object value) { 036 if (value == null) 037 throw new IllegalArgumentException("Parameter must not be null"); 038 } 039 040 /** 041 * Ensures that the condition {@code condition} holds. 042 * @param condition The condition to check 043 * @param message error message 044 * @throws IllegalArgumentException if the condition does not hold 045 * @see #ensureThat(boolean, Supplier) 046 */ 047 public static void ensureThat(boolean condition, String message) { 048 if (!condition) 049 throw new IllegalArgumentException(message); 050 } 051 052 /** 053 * Ensures that the condition {@code condition} holds. 054 * 055 * This method can be used when the message is not a plain string literal, 056 * but somehow constructed. Using a {@link Supplier} improves the performance, 057 * as the string construction is skipped when the condition holds. 058 * @param condition The condition to check 059 * @param messageSupplier supplier of the error message 060 * @throws IllegalArgumentException if the condition does not hold 061 * @since 12822 062 */ 063 public static void ensureThat(boolean condition, Supplier<String> messageSupplier) { 064 if (!condition) 065 throw new IllegalArgumentException(messageSupplier.get()); 066 } 067}