How elegantly make validation for the case when all fields in object are null?
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?
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")) {
}
Try this:
if (a == null && b == null && c == null)
throw new AllFieldsAreNullException();
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.
精彩评论