th3an0maly th3an0maly - 1 month ago 7
Java Question

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

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.

Answer

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.

Comments