How would I go about wanting to generate a default message template for a constraint (in a JPA entity) if no such message template is already defined on the annotation itself.
Here's what I mean. Suppose I have a JPA entity 'Dummy':
@Entity
public class Dummy {
@Column
@NotNull
Long id;
}
Also, suppose I have a ValidationMessages.properties file containing:
Dummy.id.NotNull=ID of dummy should not be null
Now, if I defined the @NotNull constraint as @NotNull(message={Dummy.id.NotNull}) all would work well, but what if I wanted to to generate the '{Dummy.id.NotNull}' template on the fly (using reflection) so I don't have to write the same standardized template on each and every constraint? I tried this using the MessageInterpolator class, but the interpolation method gets called only when the message attribute is defined, and this defeats the purpose of what I'm trying to do.
So, to make myself clear, how do I make the validator ask a chunk of my code "hey, what's the message for the constraint 'NotNull' on the field 'id' in the class 'Dummy' even though it has no message assigned (or rather, it has the default message assigned)?"
I was wrong - MessageInterpolator is being called even when no explicit message has been defined on the annotation. This pretty much answers my question. The only thing that is left is to figure out how to get the field name that is being validated.
EDIT:
In the end, I was forced to implement a MessageInterpolator class for each field passing the field name in the constructor and creating a Validator with that MessageInterpolator when a field is beeing validated. I don't find this satisfactory, but it was the only solution I could come up with.
On this note, I find it funny that there is no way to trace back the annotated element (be it Field, Method, Class or Parameter) when having access to the annotation instance. Were this possible, I would be able to get the field name dynamically, but this seems to be a "lack" of Java, so nothing can be done.