Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to know if all the variables in a Class are null?

Tags:

java

This would mean that the class was initialized, but the variables were not set.

A sample Class:

public class User {      String id = null;     String name = null;      public String getId() {         return id;     }     public void setId(String id) {         this.id = id;     }      public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     } } 

The actual class is huge that I prefer not to check if(xyz == null) for each of the variables.

like image 918
th3an0maly Avatar asked Sep 11 '12 03:09

th3an0maly


People also ask

How do you know if a class is null?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.

How do you know if something is null?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .

How do you check if a value is null or not in Java?

To check if a string is null or empty in Java, use the == operator. Let's say we have the following strings. String myStr1 = "Jack Sparrow"; String myStr2 = ""; Let us check both the strings now whether they are null or empty.


2 Answers

Another non-reflective solution for Java 8, in the line of paxdiabo's answer but without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name)         .allMatch(Objects::isNull); 

This remains quite easy to maintain while avoiding the reflection hammer.

like image 69
Didier L Avatar answered Oct 15 '22 17:10

Didier L


Try something like this:

public boolean checkNull() throws IllegalAccessException {     for (Field f : getClass().getDeclaredFields())         if (f.get(this) != null)             return false;     return true;             } 

Although it would probably be better to check each variable if at all feasible.

like image 43
arshajii Avatar answered Oct 15 '22 17:10

arshajii