Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check object empty

Tags:

java

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.

like image 652
AJF Avatar asked Jan 22 '13 16:01

AJF


People also ask

How check object values is empty?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

How do you know if a class object is empty?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

How do I check if an object is empty in node JS?

if (isEmptyObject(query)) { // There are no queries. } else { // There is at least one query, // or at least the query object is not empty. } Show activity on this post. If using underscore or jQuery, you can use their isEmpty or isEmptyObject calls.

How do you check if all keys of an object are empty?

keys() is a static method that returns an Array when we pass an object to it, which contains the property names (keys) belonging to that object. We can check whether the length of this array is 0 or higher - denoting whether any keys are present or not. If no keys are present, the object is empty: Object.


1 Answers

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.

like image 101
Jack Avatar answered Sep 29 '22 08:09

Jack