8013712: Add Objects.nonNull and Objects.isNull
authormduigou
Mon, 06 May 2013 20:54:42 -0700
changeset 17431 335d87f0d817
parent 17430 c445531b8f6b
child 17432 efdf6eb85a17
8013712: Add Objects.nonNull and Objects.isNull Reviewed-by: mchung, darcy
jdk/src/share/classes/java/util/Objects.java
jdk/test/java/util/Objects/BasicObjectsTest.java
--- a/jdk/src/share/classes/java/util/Objects.java	Mon May 06 14:17:59 2013 -0700
+++ b/jdk/src/share/classes/java/util/Objects.java	Mon May 06 20:54:42 2013 -0700
@@ -226,4 +226,40 @@
             throw new NullPointerException(message);
         return obj;
     }
+
+    /**
+     * Returns {@code true} if the provided reference is {@code null} otherwise
+     * returns {@code false}.
+     *
+     * @apiNote This method exists to be used as a
+     * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
+     *
+     * @param obj a reference to be checked against {@code null}
+     * @return {@code true} if the provided reference is {@code null} otherwise
+     * {@code false}
+     *
+     * @see java.util.function.Predicate
+     * @since 1.8
+     */
+    public static boolean isNull(Object obj) {
+        return obj == null;
+    }
+
+    /**
+     * Returns {@code true} if the provided reference is non-{@code null}
+     * otherwise returns {@code false}.
+     *
+     * @apiNote This method exists to be used as a
+     * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
+     *
+     * @param obj a reference to be checked against {@code null}
+     * @return {@code true} if the provided reference is non-{@code null}
+     * otherwise {@code false}
+     *
+     * @see java.util.function.Predicate
+     * @since 1.8
+     */
+    public static boolean nonNull(Object obj) {
+        return obj != null;
+    }
 }
--- a/jdk/test/java/util/Objects/BasicObjectsTest.java	Mon May 06 14:17:59 2013 -0700
+++ b/jdk/test/java/util/Objects/BasicObjectsTest.java	Mon May 06 20:54:42 2013 -0700
@@ -40,6 +40,8 @@
         errors += testToString();
         errors += testToString2();
         errors += testCompare();
+        errors += testRequireNonNull();
+        errors += testIsNull();
         errors += testNonNull();
         if (errors > 0 )
             throw new RuntimeException();
@@ -158,7 +160,7 @@
         return errors;
     }
 
-    private static int testNonNull() {
+    private static int testRequireNonNull() {
         int errors = 0;
         String s;
 
@@ -206,4 +208,22 @@
         }
         return errors;
     }
+
+    private static int testIsNull() {
+        int errors = 0;
+
+        errors += Objects.isNull(null) ? 0 : 1;
+        errors += Objects.isNull(Objects.class) ? 1 : 0;
+
+        return errors;
+    }
+
+    private static int testNonNull() {
+        int errors = 0;
+
+        errors += Objects.nonNull(null) ? 1 : 0;
+        errors += Objects.nonNull(Objects.class) ? 0 : 1;
+
+        return errors;
+    }
 }