MyNameIsHans MyNameIsHans - 1 year ago 82
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download