[Java] Validate constrain in code level

For DTO validation, normally it will implement in different class property and trigger with @Validate annotation. However, it will not be trigger when method call due to performance issue.

We can trigger the checking in code. And it is recommend for API response after collect API response.

Code to validate response in code level, it can be move to abstract class or interface and call it when needed.

import javax.validation.ConstraintViolation;

ApiResponse response = ApiClient.get();
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<ApiResponse>> result = validator.validate(response);
if(!result.isEmpty()) {
  String message = result.stream()
  .map(o-> new StringBuilder()
  .append(o.getPropertyPath().toString())
  .append(o.getMessage()))
  .collect(Collectors.joining(";\r\n"));
  throw new IllegalArgumentException(message);
}

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.