0

I am reading the Java Reference by Herber Schildt. I found a note in one of the annotations section that says:

An annotation on a local variable declaration is not retained in the .class file.

Why annotation is not retained on local variable declaration in .class file?

Stack Overflow
  • 1
  • 5
  • 23
  • 51
  • My guess would be because it exists only within that scope, so it would not be visible outside of its scope. – Marshall Tigerus May 03 '19 at 15:15
  • 10
    You access annotations using the reflection API; you can't access local variables with reflection. – Andy Turner May 03 '19 at 15:18
  • @AndyTurner - that only applies to annotations with `RetentionPolicy.RUNTIME`; there are also `SOURCE` and `CLASS` policies. – guest May 03 '19 at 15:47

1 Answers1

2

To get a concrete reason you'd need to talk to the people who designed the feature.

However, as general background, understand that there are actually three different ways that annotations can be handled, per the RetentionPolicy meta-annotation (and yes, I picked the 1.5 JavaDoc intentionally):

  • SOURCE means that the annotation exists only in the source code, and is not written into the classfile at all. It's intended for annotations that change the behavior of the compiler, but shouldn't matter at all to the running program.
  • RUNTIME means that the annotation is written into the classfile in a way that is visible to the program via reflection. As noted in the comments, you can't reflect on a local variable.
  • CLASS means that the annotation is written into the classfile in a way that is not visible to the program. They can, however, be read by bytecode analyzers or classloaders.

Annotations appear in the classfile as an attribute of a class, method, or field. The idea of a table of attributes attached to these entities has been around since the class file format was defined, so adding annotations to them was easy. The LocalVariableType, however, doesn't have per-variable attributes.

So, I speculate that the architects of the JVM decided that the benefit of load-time-only local variable annotations was not worth the changes to the data structures used to manage the local variable table.

guest
  • 871
  • 4
  • 5