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.
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With