Annotation for local variables is not retained in class file

I just found that after compilation, the annotations for exception variable of catch block (actually also for all local varialbes) are not retained. For example, for the code below:
try { } catch (@MyAnnotation e: Exception) { }

the @MyAnnotation is not present in class file. I read that Java retains annotations for local variables since 8. I am using Maven and kotlin plugin, and have set jvmTarget to 1.8. The Kotlin version that I use (and also the kotlin maven plugin version) is 1.2.30. Is there anything that I missed?

1 Like

Hello, have you tried to decompile some Java sources with local variable annotations? For example:

Ann.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.LOCAL_VARIABLE)
public @interface Ann {
}

JavaTest.java

public class JavaTest {
    public static void main(String[] args) {
        @Ann String s = "hello";
    }
}

Invoke javap -l -v -c -s JavaTest.class on the class file - there are no mentions of the Ann annotation.

According to specification "An annotation on a local variable declaration is never retained in the binary representation. "
https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.4.2

Thank you for suggestion, really appreciate that.

Thank you for the info, I knew before 8 they are not retained, but thought it’s solved in 8. Thanks for making it clear it’s not.