Java: How to check if object is null?

前端 未结 9 1308
甜味超标
甜味超标 2021-01-30 08:11

I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.

While trying to execute the f

相关标签:
9条回答
  • 2021-01-30 08:23

    if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

    0 讨论(0)
  • 2021-01-30 08:25

    Edited Java 8 Solution:

    final Drawable drawable = 
        Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
            .orElseGet(() -> getRandomDrawable());
    

    You can declare drawable final in this case.

    As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.

    0 讨论(0)
  • 2021-01-30 08:33
    Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
    if (drawable == null) {
        drawable = getRandomDrawable();
    }
    

    The equals() method checks for value equality, which means that it compares the contents of two objects. Since null is not an object, this crashes when trying to compare the contents of your object to the contents of null.

    The == operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null references) are also equal.

    0 讨论(0)
  • 2021-01-30 08:38

    Use google guava libs to handle is-null-check (deamon's update)

    Drawable drawable = Optional.of(Common.getDrawableFromUrl(this, product.getMapPath())).or(getRandomDrawable());
    
    0 讨论(0)
  • 2021-01-30 08:43
    drawable.equals(null)
    

    The above line calls the "equals(...)" method on the drawable object.

    So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"

    But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"

    To check whether an object exists and it is not null, use the following

    if(drawable == null) {
        ...
        ...
    }
    

    In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking

    null == null
    

    is valid.

    0 讨论(0)
  • 2021-01-30 08:46

    DIY

    private boolean isNull(Object obj) {
        return obj == null;
    }
    

    Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
    if (isNull(drawable)) {
        drawable = getRandomDrawable();
    }
    
    0 讨论(0)
提交回复
热议问题