It alsoThis can be done withoutfairly easily using reflection.
The solution is dynamic. When your class is extended with new fields, you don't need to add them to a list or add another null check.Lombok generated equals
and a static EMPTY
object:
import lombok.Data;
public class EmptyCheck {
public static void main(String[] args) {
User user1 = new User();
User user2 = new User();
user2.setName("name");
System.out.println(user1.isEmpty()); // prints true
System.out.println(user2.isEmpty()); // prints false
}
@Data
public static class User {
private static final User EMPTY = new User();
private String id;
private String name;
private int age;
public boolean isEmpty() {
return this.equals(EMPTY);
}
}
}
NotePrerequisites:
I used the EqualsAndHashCode annotation by Lombok.
- Default constructor should not be implemented with custom behavior as that is used to create the
EMPTY
object - All fields of the class should have an implemented
equals
(built-in Java types are usually not a problem, in case of custom types you can use Lombok)
You have to make sure the default constructor is not implemented with custom behavior and your fields does not have a default value other than the built-in java default (null for reference types, 0 for int, etc.).Advantages:
@EqualsAndHashCode
public class User
{
private static User EMPTY = new User();
private String id = null;
private String name = null;
private User()
{
}
public User(String id, String name)
{
this.id = id;
this.name = name;
}
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;
}
public boolean isEmpty()
{
return this.equals(EMPTY);
}
}
- No reflection involved
- As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the
equals
implementation - Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is
int
it checks for0
, in case ofboolean
forfalse
, etc.)