th3an0maly th3an0maly - 1 year ago 72
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) { = id;

public String getName() {
return name;
public void setName(String name) { = name;

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download