I’ve been exploring lately the different areas of programming and wanted to write something about validation so that I remember what I did. Validation means that we make sure the object has the right content (e.g fields are not null) before we process it further. In Java, the easiest way I found to do this is by using the JavaEE bean validation that works quite well with Java SE.
To do so, add in your pom.xml
:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
</dependency>
hibernate-validator
is the implementation of JavaEE bean validation, and javax.el
is needed to make hibernate-validator
happy.
From there on, you can annotate your object with the relevant annotations:
class Test {
@NotNull String dummy;
}
The list of built-in annotations can be found here. You can also add your own custom validations by defining your own annotations and implementation of the check. More details here. Finally, you can validate and get a list of violations on your object by running:
void run() {
Test test = new Test();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
// set should have 1 violations since field 'dummy' is null
Set<ConstraintViolation<Test>> nullMfgViolations = validator.validate(test);
}