I have a problem and its kind of difficult to describe, so I start from a sample:
public boolean example(DataObject object) {
boolean isValid = false;
/**
* ClassA, ClassB, ... extend from DataObject
*/
if (object.getClass().equals(ClassA.class)) {
ClassA obj = (ClassA) object;
Set<ConstraintViolation<ClassA>> violations = validator.validate(obj);
Iterator it = violations.iterator();
if (it.hasNext()) {
while (it.hasNext()) {
ConstraintViolation<ClassA> message = (ConstraintViolation<ClassA>) it.next();
// Handling my errors messages... message.getMessage();
}
} else {
isValid = true;
}
} else if (object.getClass().equals(ClassB.class)) {
Class<?> obj = (ClassB) object;
Set<ConstraintViolation<ClassB>> violations = validator.validate(obj);
Iterator it = violations.iterator();
if (it.hasNext()) {
while (it.hasNext()) {
ConstraintViolation<ClassB> message = (ConstraintViolation<ClassB>) it.next();
// Handling my errors messages... message.getMessage();
}
} else {
isValid = true;
}
}
return isValid;
}
When you read the code above, you might notice that I repeat my code in each IF bloc. The only difference are the generics... (ClassA, ClassB). Hence the fact that there are 7 subclasses in the future. (7 if bloc's in the future).
Is there a possibility to make this generics variable so it would result in :
public boolean example(DataObject object) {
boolean isValid = false;
ClassType type = object.class;
type obj = (type ) object;
Set<ConstraintViolation<type >> violations = validator.validate(obj);
Iterator it = violations.iterator();
if (it.hasNext()) {
while (it.hasNext()) {
ConstraintViolation<type > message = (ConstraintViolation<type >) it.next();
// Handling my errors messages... message.getMessage();
}
} else {
isValid = true;
}
return isValid;
}
Additional information:
I am trying to validate my objects by Annotation validation JSR303 (Hibnernate validation). The error messages will be send to a central service which will hold all the messages occurred in validations.
Thanks for your time
PS : If problem is not clear, please warn me and I'll try to rewrite...


Sign In
Create Account


Back to top









