MyNameIsHans MyNameIsHans - 4 months ago 10
Java Question

Are references to Annotations constant?

if I call

on the same
with the same
Class<? extends Annotation>
as parameter, will the result always be the same instance of the annotation's

I know that
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.