集册 Java实例教程 从Objects类测试requireNonNull(T obj,String message)

从Objects类测试requireNonNull(T obj,String message)

欢马劈雪     最近更新时间:2020-01-02 10:19:05

731
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
从Objects类测试requireNonNull(T obj,String message)
//来自 时   代    Java - nowjava.com

import java.util.Objects;

import java.util.function.Supplier;


public class Main {

  public static void main(String[] args) {

    // Testing requireNonNull(T obj, String message)

    try {

      printName("test");

      printName(null);

    } catch (NullPointerException e) {

      System.out.println(e.getMessage());

    }


    // requireNonNull(T obj, Supplier<String> messageSupplier)

    try {

      Supplier<String> messageSupplier = () -> "Name is required. ";/*时代Java公众号*/

      printNameWithSuplier("aaa", messageSupplier);

      printNameWithSuplier(null, messageSupplier);

    } catch (NullPointerException e) {

      System.out.println(e.getMessage());

    }

  }

  public static void printName(String name) {

    // Test name for not null. Generate a NullPointerException if it is null.

    Objects.requireNonNull(name, "Name is required.");


    // Print the name if the above statement dod not throw an exception

    System.out.println("Name is " + name);

  }


  public static void printNameW
展开阅读全文