I am writing code that has explicit call to Bean Validation (JSR-303) something like this:
public class Example {
@DecimalMin(value = "0")
private static final String ANNOTATED = "";
public void isPossitiveNumber(String str){
ValidatorFactory factory =
Validation.buildDefaultValidatorFactory();
ConstraintValidator<DecimalMin, String>
validator =
factory.getConstraintValidatorFactory().getInstance(
DecimalMinValidatorForString.class);
validator.initialize(
ReflectionUtils.findField(getClass(), "ANNOTATED")
.getAnnotation(
DecimalMin.class));
boolean isValid = validator.isValid(str, null);
return isValid;
}
}
Note the line boolean isValid = validator.isValid(str, null);
I transfer null
for ConstraintValidatorContext
because I found no way to obtain/construct it. In this particular case, this if fine, because there is no use of the ConstraintValidatorContext
internally, but it is obvious a hack. How should I get ConstraintValidatorContext
?
ADDED
I was asked to provide use-cases. So, for example, I am writting custom validator and I want to reuse exisiting validations. Or I am writting plane Java code as desribed above and I want to reuse exisiting validation.
javax.validation.Validator
API, not by creating and invoking constraint validators by hand.ConstraintValidatorContext
is passed by the engine to validators during validation, so its implementation is typically not exposed to users. – Anthropomorphosis