JDK-6889858 : Add nonNull methods to java.util.Objects
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util
  • Affected Version: 7
  • Priority: P3
  • Status: Resolved
  • Resolution: Fixed
  • OS: generic
  • CPU: generic
  • Submitted: 2009-10-08
  • Updated: 2017-05-16
  • Resolved: 2009-10-24
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 7
7 b75Fixed
Related Reports
Relates :  
Relates :  
Relates :  
Relates :  
Description
From Josh on ###@###.###
(http://mail.openjdk.java.net/pipermail/core-libs-dev/2009-October/002891.html)

I strongly suggest that you do add these two methods:

    /**
     * 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:
     * <pre>
     * public Foo(Bar bar) {
     *     this.bar = Objects.nonNull(bar);
     * }
     * </pre>
     *
     * @param obj the object reference to check for nullity
     * @return {@code obj} if not {@code null}
     * @throws NullPointerException if {@code obj} is {@code null}
     */
    public static <T> 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:
     * <pre>
     * 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");
     * }
     * </pre>
     *
     * @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
     * @return {@code obj} if not {@code null}
     * @throws NullPointerException if {@code obj} is {@code null}
     */
    public static <T> T nonNull(T obj, String message) {
        if (obj == null)
            throw new NullPointerException(message);
        return obj;
    }

They do a great job reducing the verbiage in validity-checking of arguments that must not be null.

Comments
PUBLIC COMMENTS See http://hg.openjdk.java.net/jdk7/tl/jdk/rev/1602e8848bde
2009-10-19

EVALUATION A fine idea to consider.
2009-10-08