41

Basically how do you check if an object is null or empty. What I mean is that if I have an object instantiated but all its values or fields are null, the how do I check in code if it is empty?

I have tried;

if (doc != null){
.... do something

But it doesn't seem to work.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
AJF
  • 1,801
  • 4
  • 27
  • 54
  • 3
    How does it not work? How does your object look like? What is doc here? – Rohit Jain Jan 22 '13 at 16:28
  • references can be null but objects cannot be null. An object may have a method called `isEmpty()` This doesn't mean it doesn't use any memory and it could use the same amount of memory when full. e.g. ArrayBlockingQueue. It is a method which states the object doesn't contain any other objects you can obtain. This is something only the developer of the component can determine. – Peter Lawrey Jan 22 '13 at 16:38

9 Answers9

45

You can't do it directly, you should provide your own way to check this. Eg.

class MyClass {
  Object attr1, attr2, attr3;

  public boolean isValid() {
    return attr1 != null && attr2 != null && attr3 != null;
  }
}

Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Perhaps this could be done using java.lang.reflect, but it could be error-prone... – Bastien Jansen Jan 22 '13 at 16:30
  • Yes, but before requiring reflection to do this work I would worry about the needs of having uninitialized fields that are `null`. That's always the same problem with null values. – Jack Jan 22 '13 at 16:32
  • I totally agree with you on this. Perhaps the OP has a wrong requirement (but he does not explain why he needs to check this). – Bastien Jansen Jan 22 '13 at 16:34
  • @Nebelmann reflection ? Why the hell would you use that, this is just basic oo/encapsualtion issue – NimChimpsky Jan 22 '13 at 16:42
  • I set values of all my variables at once and I have about 20 variables . Instead of writing a return check for all 20 variables as null, I can simply return a check of null for one variable write ? – Ace McCloud Apr 30 '15 at 18:27
18
import org.apache.commons.lang3.ObjectUtils;
if(ObjectUtils.isEmpty(yourObject)){
  //your block here
}
Alekhya Yalla
  • 252
  • 3
  • 10
  • 4
    It works only on CharSequence, Collection and Map. It will always return false for a custom Object. (Cf. method implementation) – Anto Jan 19 '22 at 08:25
8

This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this)!=null) {
                return false;
            }
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
        }
    }
    return true;
}
Lokeshkumar R
  • 575
  • 5
  • 13
  • 1
    Can this be made to work to any depth by calling recursively on its sub-objects? I tried this but got hung up on sub-objects like Long and String which have other stuff inside them and getDeclaredFields() is returning multiple sub-objects. – mojoken May 17 '19 at 15:51
3

You should check it against null.

If you want to check if object x is null or not, you can do:

    if(x != null)

But if it is not null, it can have properties which are null or empty. You will check those explicitly:

    if(x.getProperty() != null)

For "empty" check, it depends on what type is involved. For a Java String, you usually do:

    if(str != null && !str.isEmpty())

As you haven't mentioned about any specific problem with this, difficult to tell.

Swapnil
  • 8,201
  • 4
  • 38
  • 57
3

I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.

To check for Collection be empty or null

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

or use Apache Commons CollectionUtils.isEmpty()

To check if Map is empty or null

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}

or use Apache Commons MapUtils.isEmpty()

To check for String empty or null

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

or use Apache Commons StringUtils.isBlank()

To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.

supernova
  • 3,111
  • 4
  • 33
  • 30
1

for simple (It's worked in my project). if null check not mandatory for some fields then exclude it from toString() method as in my above code, I have removed school.

public class Student {
    private String name;
    private String school;
    private Integer roll;
    private String section;
    //getters and setters

    @Override
    public String toString() {
        return "Student [name=" + name + ", roll=" + roll + ", section=" + section + "]";
    }

}


public class StudentRunner {
    
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("ved");
        s.setRoll(12);
        s.setSection("A");
        s.setSchool(null);//school set null and it removed from toString() method
        if(s.toString().contains("null")) {
            System.out.println("null value contains");
            //do your work here or throw exception
        } else {
            System.out.println("no null value");
        }
    }

}

output : no null value

Onic Team
  • 1,620
  • 5
  • 26
  • 37
0

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

I have a way, you guys tell me how good it is.

Create a new object of the class and compare it with your object (which you want to check for emptiness).

To be correctly able to do it :

Override the hashCode() and equals() methods of your model class and also of the classes, objects of whose are members of your class, for example :

Person class (primary model class) :

public class Person {

    private int age;
    private String firstName;
    private String lastName;
    private Address address;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + age;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (age != other.age)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
                + "]";
    }

}

Address class (used inside Person class) :

public class Address {

    private String line1;
    private String line2;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
        result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Address other = (Address) obj;
        if (line1 == null) {
            if (other.line1 != null)
                return false;
        } else if (!line1.equals(other.line1))
            return false;
        if (line2 == null) {
            if (other.line2 != null)
                return false;
        } else if (!line2.equals(other.line2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Address [line1=" + line1 + ", line2=" + line2 + "]";
    }

}

Now in the main class :

    Person person1 = new Person();
    person1.setAge(20);

    Person person2 = new Person();

    Person person3 = new Person();

if(person1.equals(person2)) --> this will be false

if(person2.equals(person3)) --> this will be true

I hope this is the best way instead of putting if conditions on each and every member variables.

Let me know !

Abhinav
  • 403
  • 4
  • 16
-4

let suppose ,

data = {};

if( if(!$.isEmptyObject(data)))
{
     document.write("Object is empty);
}

else{
    document.write("Object is not empty);
}

It worked for me and its an easy way to check if object is empty or not