精华内容
下载资源
问答
  • Java Objects.requireNonNull

    2020-11-21 14:28:11
    在学习java动态代理,看到Proxy类中Objects.requireNonNull(T)及Objects.requireNonNull(T obj, String message)来判断传入方法的参数是否为null并抛出异常信息 例如: public void doSomething(String ...

    在学习java动态代理,看到Proxy类中Objects.requireNonNull(T)Objects.requireNonNull(T obj, String message)来判断传入方法的参数是否为null并抛出异常信息

    例如:

    public void doSomething(String customerName, Integer age) {
        Objects.requireNonNull(customerName, "customerName cannot be null");
        Objects.requireNonNull(age, "age cannot be null");
        ...
    }

    但这和使用if(obj==null)判断是否为null的有什么差别呢

    其实javaAPI文件就有说明了,主要就是用来验证方法输入参数是否为null,例如之前通常写法如下:

    public Foo(Bar bar) {
        if(bar == null) {
            throw new NullPointerException();
        } else {
            this.bar = bar;
        }
    }

    有这个方法泽可以写为:

    public Foo(Bar bar) {
        this.bar = Objects.requireNonNull(bar);
    }

    一旦传入的参数为null,会抛出NullPointerException

    Objects.requireNonNull(T)Objects.requireNonNull(T obj, String message)是Java 7才加入的工具类,源码如下:

    public static  T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }
    
    public static  T requireNonNull(T obj, String message) {
        if (obj == null)
            throw new NullPointerException(message);
        return obj;
    }

    若传入的参数不为null,则返回原参数,因此可确保传入的参数不为null

    简言之就是不需要每次都要自己用if()判断传入参数是否为null了,

    好处是可读性佳,从名称就可以清楚知道的接收得参数应为null,且可直接给定错误信息。搭配写在方法的开头位置,可链到fail-fast的设计目的

     

    而java 8 可以用Optional.of(T val)替代,例如:

    public Foo(Bar bar) {
         this.bar = Optional.of(bar).get();
         // or
         this.bar = Optional.of(s).orElseThrow(() -> new NullPointerException("bar cannot be null"));
    }

     

    展开全文
  • Why should one use Objects.requireNonNull() ?I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object (argumen...

    Why should one use Objects.requireNonNull() ?

    I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object (argument) is null.

    public static T requireNonNull(T obj) {

    if (obj == null)

    throw new NullPointerException();

    return obj;

    }

    But NullPointerException will be thrown anyway if a null object is dereferenced. So, why should one do this extra null check and throw

    NullPointerException?

    One obvious answer (or benefit) is that it makes code more readable and I agree. I'm keen to know any other reasons for using

    Objects.requireNonNull() in the beginning of the method.

    解决方案

    Because you can make things explicit by doing so. Like:

    public class Foo {

    private final Bar bar;

    public Foo(Bar bar) {

    Objects.requireNonNull(bar, "bar must not be null");

    this.bar = bar;

    }

    Or shorter:

    this.bar = Objects.requireNonNull(bar, "bar must not be null");

    Now you know:

    when a Foo object was successfully created using new()

    then its bar field is guaranteed be non-null.

    Compare that to: you create a Foo object today, and tomorrow you invoke a method that uses that field and throws. Most likely, you will not know tomorrow why that reference was null yesterday when it got passed to the constructor!

    In other words: by explicitly using this method to check incoming references you can control the point in time when the exception will be thrown. And most of the time, you want to fail as fast as possible!

    The major advantages are:

    as said, controlled behavior

    easier debugging - because you throw up in the context of the object creation. At a point in time where you have a certain chance that your logs/traces tell you what went wrong!

    and as shown above: the true power of this idea unfolds in conjunction with final fields. Because now any other code in your class can safely assume that bar isn't null - and thus you do not need any if (bar == null) checks in other places!

    展开全文
  • Objects.requireNonNull( )方法说明

    千次阅读 2019-09-22 20:22:59
    Objects.requireNonNull( )方法在java.util.Objects中 作用就是判断一个对象是否为空 /* @param obj 需要检测是否为空的对象 * @param <T> 对象类型 * @return 对象不为空则返回该对象 * @throws 对象为空...

    Objects.requireNonNull( )方法在java.util.Objects中
    作用就是判断一个对象是否为空

    /* @param obj 需要检测是否为空的对象
         * @param <T> 对象类型
         * @return 对象不为空则返回该对象
         * @throws 对象为空则报NullPointerException异常
         */
        public static <T> T requireNonNull(T obj) {
            if (obj == null)
                throw new NullPointerException();
            return obj;
        }
    
    

    空的时候报空指针异常

    展开全文
  • Objects.requireNonNull()说明

    千次阅读 2019-07-24 19:26:05
    今天看ArrayList源码时偶然看到了Objects.requireNonNull()这个方法,有点好奇就看了一下,下面是这个方法的源码: public static <T> T requireNonNull(T obj) { if (obj == null) throw new ...

    今天看ArrayList源码时偶然看到了Objects.requireNonNull()这个方法,有点好奇就看了一下,下面是这个方法的源码:

    public static <T> T requireNonNull(T obj) {
            if (obj == null)
                throw new NullPointerException();
            return obj;
        }

    可以看到这是个带有泛型的静态方法,具体作用就是判断对象是否为null,如果是null就报空指针异常,不为null直接返回这个对象。

    展开全文
  • 使用Objects.requireNonNull(d)方法,若d为null,则会抛出空指针异常-Exception in thread "main" java.lang.NullPointerException,会中断程序的运行。则仍需要外城方法捕捉异常。代码如下: try { Objects....
  • Objects.requireNonNull方法说明

    万次阅读 2017-07-20 09:22:13
     今天看源码的时候看见下面的方法,虽然猜到它的含义,但毕竟...Objects.requireNonNull(h); import java.util.Objects类里下面详细实现:  public static T requireNonNull(T obj) {  if (obj == null)
  • Objects.requireNonNull(obj, message)是java7新增的特性,用于替代手工null值检查。 具体实现如下: public static <T> T requireNonNull(T obj, String message) { if (obj == null) throw new ...
  • Objects.requireNonNull()

    2018-06-07 14:11:55
    Objects.requireNonNull(holder).itemView.setTag(dataBean); 源码 /** * Checks that the specified object reference is not {@code null}. This * method is designed primarily for doing parameter ...
  • at java.util.Objects.requireNonNull(Objects.java:203) at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:191) at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:173) at org.jenkinsci....
  • Objects.requireNonNull() 如果当前对象为空 会抛出一个空指针异常 否则就会返回当前对象 。 常用于非空校验, 越早校验,越早发现
  • 异常处理之Objects.requireNonNull( )方法说明 1. 使用场景 判断对象为不为空,可以使用Objects.requireNonNull( )方法对对象进行判断。 2.源码 /* @param obj 需要检测是否为空的对象 * @param <T> 对象...
  • 理解一下 Java 的 Objects.requireNonNull(),参考 这里,截图如下,这种处理叫做 fail fast,其实就是方便了使用者,否则,使用者需要自己去进行入参保护。 这个时候想起了两个小插曲: 当年去华为面试,算法其实...
  • 如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常
  • System.out.println(Objects.hashCode(obj)); System.out.println(Objects.toString(obj));... System.out.println(Objects.requireNonNull(obj, "obj参数不能为空")); output: 0 null E...
  • IDEA中习惯跟踪源码实现逻辑,多次碰到Objects.requireNonNull(T obj)这个方法,改方法主要用于提早判断对象是否为空,以便更早的抛出NPE 平时小组开发中强调程序健壮性,不允许组员的代码中出现明显的NPE,这样多数...
  • import java.util.Objects; import java.util.Optional; public class OfAndOfNullable { public static void main(String[] args) { String str1 = "A"; String str2 = "B"; String str3 = null; Objects....
  • 这也是 requireNonNull 这个方法的设计思想, 让错误尽早出现. 使用这个方法, 我们明确的抛出异常, 发生错误时, 我们立刻抛出异常. requireNonNull 方法有一个重载方法, 可以提供一个报错信息, 以供我们 debug 的...
  • package org.ziegler.javabase.thread;...import java.util.Objects; public class RequiredNonNullSample { private Ball ball; private List<Ball> ballBucket = new ArrayList<>(); Requi.
  • * this.bar = Objects.requireNonNull(bar, "bar must not be null"); * this.baz = Objects.requireNonNull(baz, "baz must not be null"); * } * </pre></blockquote> * * @param obj the object reference ...
  • Objects.requireNonNull(T obj)方法记录

    千次阅读 2018-12-07 13:59:25
    判断一个对象为空抛出NullPointer异常的方法  实现: public static &... T requireNonNull(T obj) {  if (obj == null)  throw new NullPointerException();  return obj; }    ...
  • 题主先不下结论,给出一些例证,每个看官自己体会有没有加的必要,先贴出requireNonNull这个方法。 public static <T> T RunTime(T obj) { if (obj == null) throw new NullPointerException(); return ...
  • Objects.requireNonNull(obj,"传递的对象的值是null");

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 17,545
精华内容 7,018
关键字:

objects.requirenonnull