Reputation: 14373
I want to validate a Java class object to check if the members obey certain rules. Except for specific rules, I also want to check if there are any string members which are null/empty.
What is a good way of doing so (Validating the string members)?
My approach is:
if(StringUtils.isNotEmpty(sMember1) && StringUtils.isNotEmpty(sMember2)...)
Is there a concise approach of validating all members which are Strings?
(Is Reflection a possibility? If yes, will it be an expensive operation?)
Upvotes: 1
Views: 3774
Reputation: 13057
I also recommend to use JSR 303 as @krishnakumarp pointed out, and I wouldn't build my own framework, but use anything that's already available. However, if you'd like to learn how you could implement it, then it's actually quite simple:
public static Collection<ErrorMessage> validate(Object obj) {
Collection<ErrorMessage> errors = new ArrayList<ErrorMessage>();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.getType().equals(String.class)) {
try {
String value = (String) field.get(obj);
if (isEmpty(value)) {
errors.add(new ErrorMessage(field.getName() + " is empty"));
}
}
catch (Exception e) {
// oops.
e.printStackTrace();
}
}
}
return errors;
}
Please note, that in this example, there is a custom error handling and for each validation error an ErrorMessage
object is created.
Upvotes: 1
Reputation: 3288
Why don't you consider checking the validity of the members when they are set using setters methods of the same object? It is good to check for the validity of the members of objects before making any operations done on them, but IMO it is good to validate as soon as they are set. If the values are inappropriate, allow the operations(inside the core classes) to throw proper exception to the higher layer.
Note: This approach is feasible if you are not re-factoring a legacy snippets, but you are writing new data objects.
Upvotes: 0
Reputation: 9295
You should use jsr 303 compliant validators. Please see this discussion Is there an implementation of JSR-303 (bean validation) available?
Upvotes: 2
Reputation: 24630
There are a lot of frameworks and libs for that. Look at http://oval.sourceforge.net/
Upvotes: 0