Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8138963

java.lang.Objects new method to default to non-null

    Details

    • Type: Enhancement
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: 9
    • Fix Version/s: 9
    • Component/s: core-libs
    • Labels:
    • Subcomponent:
    • Resolved In Build:
      b89

      Backports

        Description

        java.util.Objects includes a number of convenience methods to make it easier to work with references that may be null, typically by conditionally substituting a default value for a null object reference.

        Methods should be added:

             /**
             * Returns the first argument if it is not {@code null} and
             * otherwise returns the non-null second argument.
             *
             * @param obj an object
             * @param defaultObj a non-null object to return if the first argument
             * is {@code null}
             * @param <T> the type of the reference
             * @return the first argument if it is not {@code null} and
             * otherwise the second argument if it is not null
             * @throws NullPointerException if both {@code obj} is null and
             * {@code nullDefault} is {@code null}
             * @since 9
             */
            public static <T> T nonNullElse(T obj, T defaultObj) {
                return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
            }

            /**
             * Returns the first argument if it is not {@code null} and otherwise
             * returns the non-null value of {@code supplier.get()}.
             *
             * @param obj an object
             * @param supplier of a non-null object to return if the first argument
             * is {@code null}
             * @param <T> the type of the reference
             * @return the first argument if it is not {@code null} and otherwise
             * the value from {@code supplier.get()} if it is not {@code null}
             * @throws NullPointerException if both {@code obj} is null and
             * either the {@code supplier} is {@code null} or
             * the {@code supplier.get()} value is {@code null}
             * @since 9
             */
            public static <T> T nonNullElseGet(T obj, Supplier<? extends T> supplier) {
                return (obj != null) ? obj : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
            }

          Attachments

            Issue Links

              Activity

                People

                • Assignee:
                  rriggs Roger Riggs
                  Reporter:
                  rriggs Roger Riggs
                • Votes:
                  0 Vote for this issue
                  Watchers:
                  4 Start watching this issue

                  Dates

                  • Created:
                    Updated:
                    Resolved: