--- old/src/share/classes/java/util/Objects.java 2009-10-19 16:28:53.000000000 -0700 +++ new/src/share/classes/java/util/Objects.java 2009-10-19 16:28:52.000000000 -0700 @@ -107,4 +107,50 @@ public static int compare(T a, T b, Comparator c) { return (a == b) ? 0 : c.compare(a, b); } + + /** + * Checks that the specified object reference is not {@code null}. This + * method is designed primarily for doing parameter validation in methods + * and constructors, as demonstrated below: + *
+     * public Foo(Bar bar) {
+     *     this.bar = Objects.nonNull(bar);
+     * }
+     * 
+ * + * @param obj the object reference to check for nullity + * @param the type of the reference + * @return {@code obj} if not {@code null} + * @throws NullPointerException if {@code obj} is {@code null} + */ + public static T nonNull(T obj) { + if (obj == null) + throw new NullPointerException(); + return obj; + } + + /** + * Checks that the specified object reference is not {@code null} and + * throws a customized {@link NullPointerException} if it is. This method + * is designed primarily for doing parameter validation in methods and + * constructors with multiple parameters, as demonstrated below: + *
+     * public Foo(Bar bar, Baz baz) {
+     *     this.bar = Objects.nonNull(bar, "bar must not be null");
+     *     this.baz = Objects.nonNull(baz, "baz must not be null");
+     * }
+     * 
+ * + * @param obj the object reference to check for nullity + * @param message detail message to be used in the event that a {@code + * NullPointerException} is thrown + * @param the type of the reference + * @return {@code obj} if not {@code null} + * @throws NullPointerException if {@code obj} is {@code null} + */ + public static T nonNull(T obj, String message) { + if (obj == null) + throw new NullPointerException(message); + return obj; + } }