When and how are annotations initialized in Java? Can I control this?

advertisements

I have specified a custom annotation for use in Java bean-validation. I use the same annotation class for all of my fields and pass a string parameter with the name of the field, like this:

@CustomConstraint(value="name")
private String name;
@CustomConstraint(value="address1")
private String addressLine1;

My constraint validator maintains a HashMap that maps String keys (name of field) to an Interface for my validation classes. I statically initialize this map by pairing particular field names with concrete subclasses of the interface that will be used to validate the field, like this:

private static final Map<String, CustomValidatorClass> fieldMapper; 

static {
    Map<String, CustomValidatorClass> map = new HashMap<String, CustomValidatorClass>();
    map.put("name", new NameValidator());
    map.put("address1", new Address1Validator());
    fieldMapper = Collections.unmodifiableMap(map);
}

My concern is that this initialization process could be quite expensive (I have dozens of fields), and that it may be initialized for every single field which I am validating. I am hoping that there is some way to specify that the annotation should be initialized once and reused, or that this is the default behavior.

EDIT: I am using JSF 2.0 along with bean-validation, so I am not directly reading or calling these annotations. That is handled by the framework, which is why I could not determine exactly how it was operating.


I did some testing and it seems that the static initialization I am doing on my map is only being called the first time I attempt to validate a field. This means that the Annotation is not being initialized repeatedly and is instead being reused for each field. My worry about overhead in my large initialization is now addressed.