Why Use the payload
Parameter?
The payload parameter is used to include information about the constraint to code handling validation errors. It allows users to augment a constraint with additional information that isn't covered in the main constraint parameters. The spec uses the example of associating a severity with a validation constraint:
package com.acme.severity;
public class Severity {
public static class Info implements Payload {};
public static class Error implements Payload {};
}
public class Address {
@NotNull(message="would be nice if we had one", payload=Severity.Info.class)
public String getZipCode() { [...] }
@NotNull(message="the city is mandatory", payload=Severity.Error.class)
String getCity() { [...] }
}
The @NotNull
annotation doesn't need to know (and can't know) about the application specific Severity
class, but the payload parameter ensures that such metadata can be associated with an annotation if needed.
In this case, you could use the severity information to differentiate between violations that only generate warnings vs actual errors that prevent a client from doing something.
How to Access the Metadata?
The payload can be accessed by retrieving the ConstraintDescriptor
from the ConstraintViolation
that is provided when the specific constraint isn't valid:
private boolean isHardError(ConstraintViolation<Address> violation) {
var descriptor = violation.getConstraintDescriptor();
Set<Class<? extends Payload>> = descriptor.getPayload();
if(payload.contains(Severity.Info.class)) {
// treat the violation as a warning
return false;
} else {
// treat the violation as an error
return true;
}
}