2

Java has a native support for annotations.

I'm wondering if when I call obj.getAnnotation(Test.class), java stores class metadata in any kind of cache.

I have the same question with reflection like:

for (Method method : obj.getDeclaredMethods()) {

        if (method.isAnnotationPresent(Test.class)) {

            Annotation annotation = method.getAnnotation(Test.class);
            Test test = (Test) annotation;

        }
}
Serginho
  • 7,291
  • 2
  • 27
  • 52

2 Answers2

2

Caching behavior isn't part of the "contract" of the getAnnotation method, but (at least in the openjdk), it does happen.

Andrew Rueckert
  • 4,858
  • 1
  • 33
  • 44
  • That's actually very interesting. Never thought of that. [This example](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/reflect/Executable.java#Executable.declaredAnnotations%28%29) is even more clear (this is where `Method.getAnnotation(...)` points) – esin88 Mar 01 '17 at 21:51
  • Annotations are used in the whole JavaEE environment. You can see reflection everywhere. It's supposed that exists a mechanism to speed-up first time code execution. Which is? For example I know that Wildfly initializes dependency injection instances at bootstrap. – Serginho Mar 02 '17 at 11:40
0

Not sure what do you mean by cache, but JVM stores all Class, field and method annotations, that are visible in runtime, in special structure, that makes them available through reflection API calls. You can find more information about this here.

Hope that's what you're looking for.

esin88
  • 3,091
  • 30
  • 35
  • Actually I'm asking if use reflection is eficient. O(1) complexity or scan the class when I call the method. – Serginho Mar 02 '17 at 08:38
  • @Serginho then you probably need Andrew Rueckert's answer, it's pretty straightforward. If your annotations were requested at least once, it's stored in some kind of cache. – esin88 Mar 02 '17 at 10:18
  • @Serginho you could accept his answer then, if that's what you were looking for – esin88 Mar 02 '17 at 10:29
  • Don't worry about that, I will do it when I clarify all doubts – Serginho Mar 02 '17 at 11:43