I have a object from the following class,
public class Customer {
private String email;
private String name;
}
How can I check whether every attribute is not null using Optional from java 8? Or there is another less verbose way?
I have a object from the following class,
public class Customer {
private String email;
private String name;
}
How can I check whether every attribute is not null using Optional from java 8? Or there is another less verbose way?
With out reflection you can't check all in one shot (as others mentioned, Optional not meant for that purpose). But if you are okay to pass all attributes
boolean match = Stream.of(email, name).allMatch(Objects::isNull);
You can have it as an util method inside your Class and use it.
How can I check whether every attribute is not null using Optional from java 8?
Optional is NOT meant for checking nulls. Rather it is intended to act as a container on your objects / fields and provide a null safe reference. The idea is to relieve programmer from checking null references for every field in a sequence of operations covering multiple fields. What you are asking for is exactly opposite of what Optional is supposed to help with.
Here is a good article explaining the purpose of Optional
.