Reputation: 3417
I want to throw exception if all fields in object are null, but traditional way for checking on null looks not very smart. What can be another way to do this?
Upvotes: 0
Views: 157
Reputation: 11308
Try this:
if (a == null && b == null && c == null)
throw new AllFieldsAreNullException();
Upvotes: 1
Reputation: 2599
EDIT : This uses reflection (java.lang.reflect.Field)
You could create a method within this object to return its valid state :
public boolean isValid() {
boolean isValid = true;
for (int i = 0; isValid && i < this.getClass().getFields().length; ++i) {
if (this.getClass().getFields()[i].equals(null)) {
isValid = false;
}
}
return isValid;
}
This way, the method is going to validate each and every field of the class so you don't need to modifiy the code whenever you add a new field to it.
HOWEVER, the primary key cannot be null, so you have NOT to validate this field, or any NOTNULL field for that matter.
if (!field.getName().equals("aPrimaryKey_OR_aNotNullField")) {
}
Upvotes: 1
Reputation: 272237
You could potentially use reflection to write a generic method to analyse fields of an object, but it doesn't seem the clearest way of performing validation. I would perhaps be explicit for clarity's sake.
Upvotes: 0