Suppliers.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.lang3.function;

  18. import java.util.function.Supplier;

  19. /**
  20.  * Helps use {@link Supplier}.
  21.  *
  22.  * @since 3.13.0
  23.  */
  24. public class Suppliers {

  25.     /**
  26.      * Returns the singleton supplier that always returns null.
  27.      * <p>
  28.      * This supplier never throws an exception.
  29.      * </p>
  30.      */
  31.     @SuppressWarnings("rawtypes")
  32.     private static Supplier NUL = () -> null;

  33.     /**
  34.      * Null-safe call to {@link Supplier#get()}.
  35.      *
  36.      * @param <T> the type of results supplied by this supplier.
  37.      * @param supplier the supplier or null.
  38.      * @return Result of {@link Supplier#get()} or null.
  39.      */
  40.     public static <T> T get(final Supplier<T> supplier) {
  41.         return supplier == null ? null : supplier.get();
  42.     }

  43.     /**
  44.      * Returns the singleton supplier that always returns null.
  45.      * <p>
  46.      * This supplier never throws an exception.
  47.      * </p>
  48.      *
  49.      * @param <T> Supplied type.
  50.      * @return The NUL singleton.
  51.      * @since 3.14.0
  52.      */
  53.     @SuppressWarnings("unchecked")
  54.     public static <T> Supplier<T> nul() {
  55.         return NUL;
  56.     }

  57.     /**
  58.      * Make private in 4.0.
  59.      *
  60.      * @deprecated TODO Make private in 4.0.
  61.      */
  62.     @Deprecated
  63.     public Suppliers() {
  64.         // empty
  65.     }
  66. }