Are references to Annotations constant?

if I call getAnnotation() on the same Field with the same Class<? extends Annotation> as parameter, will the result always be the same instance of the annotation’s class?

I know that Annotations are cached, but is there something that might clear the cache/something that might make it risky to rely on this instance?


Yes. If you look at the source code for getAnnotation it reads as follows:

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    if (annotationClass == null)
        throw new NullPointerException();

    return (T) declaredAnnotations().get(annotationClass);

the declaredAnnotations method is coded like:

private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
    if (declaredAnnotations == null) {
        declaredAnnotations = AnnotationParser.parseAnnotations(
            annotations, sun.misc.SharedSecrets.getJavaLangAccess().
    return declaredAnnotations;

And the declaredAnnotations field is a map:

private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;

In summary, the annotations are stored in the map, and the same ones are returned once they have been retrieved.

Leave a Reply

Your email address will not be published. Required fields are marked *