diff --git a/src/main/java/org/apache/commons/math/util/MathUtils.java b/src/main/java/org/apache/commons/math/util/MathUtils.java index 76b159b87..e18304df7 100644 --- a/src/main/java/org/apache/commons/math/util/MathUtils.java +++ b/src/main/java/org/apache/commons/math/util/MathUtils.java @@ -2274,4 +2274,32 @@ public final class MathUtils { System.arraycopy(source, 0, output, 0, FastMath.min(len, source.length)); return output; } + + /** + * Checks that an object is not null. + * + * @param o Object to be checked. + * @param pattern Message pattern. + * @param args Arguments to replace the placeholders in {@code pattern}. + * @throws NullArgumentException if {@code o} is {@code null}. + */ + public static void checkNotNull(Object o, + Localizable pattern, + Object ... args) { + if (o == null) { + throw new NullArgumentException(pattern, args); + } + } + + /** + * Checks that an object is not null. + * + * @param o Object to be checked. + * @throws NullArgumentException if {@code o} is {@code null}. + */ + public static void checkNotNull(Object o) { + if (o == null) { + throw new NullArgumentException(); + } + } } diff --git a/src/test/java/org/apache/commons/math/util/MathUtilsTest.java b/src/test/java/org/apache/commons/math/util/MathUtilsTest.java index 0ec914333..500877c2e 100644 --- a/src/test/java/org/apache/commons/math/util/MathUtilsTest.java +++ b/src/test/java/org/apache/commons/math/util/MathUtilsTest.java @@ -28,6 +28,8 @@ import org.apache.commons.math.exception.MathIllegalArgumentException; import org.apache.commons.math.exception.MathArithmeticException; import org.apache.commons.math.exception.MathRuntimeException; import org.apache.commons.math.exception.NotFiniteNumberException; +import org.apache.commons.math.exception.NullArgumentException; +import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.random.RandomDataImpl; /** @@ -1640,4 +1642,22 @@ public final class MathUtilsTest extends TestCase { assertEquals(0, dest[i], 0); } } + + public void testCheckNotNull1() { + try { + Object obj = null; + MathUtils.checkNotNull(obj); + } catch (NullArgumentException e) { + // Expected. + } + } + + public void testCheckNotNull2() { + try { + double[] array = null; + MathUtils.checkNotNull(array, LocalizedFormats.INPUT_ARRAY, null); + } catch (NullArgumentException e) { + // Expected. + } + } }