-1

If it define the following annotation:

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.TYPE)
public @interface MyAnnot {
    public String value();
}

And then use it defining the following interface:

@MyAnnot("somevalue")
public interface MyClass
{
}

If I then run the following commands:

javac MyClass.java

javap MyClass.class

Then my output is:

Compiled from "MyClass.java"

public interface MyClass { }

So it appears to me that the annotation does not get retained? If this is so why is this the case?

Community
  • 1
  • 1
user79074
  • 4,937
  • 5
  • 29
  • 57

2 Answers2

1

Use the -v/-verbose option to Print additional information

> javap -c -v MyClass.class 

[...]

SourceFile: "MyClass.java"
RuntimeVisibleAnnotations:
  0: #24(#25=s#26)
    org.example.MyAnnot(
      value="somevalue"
    )
Savior
  • 3,225
  • 4
  • 24
  • 48
-1

If you see the following you will notice that it does in fact have the annotation retained. It is just that javap doesn't show it in the standard output. Using the -v option for verbose does show it:

C:\Development\stack>javap -v MyClass.class
Classfile /C:/Development/stack/MyClass.class
  Last modified 12-Sep-2018; size 172 bytes
  MD5 checksum 9ca4a6c712dadb0bedeede816c57c1b4
  Compiled from "MyClass.java"
public interface MyClass
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT
Constant pool:
   #1 = Class              #9             // MyClass
   #2 = Class              #10            // java/lang/Object
   #3 = Utf8               SourceFile
   #4 = Utf8               MyClass.java
   #5 = Utf8               RuntimeVisibleAnnotations
   #6 = Utf8               LMyAnnot;
   #7 = Utf8               value
   #8 = Utf8               somevalue
   #9 = Utf8               MyClass
  #10 = Utf8               java/lang/Object
{
}
SourceFile: "MyClass.java"
RuntimeVisibleAnnotations:
  0: #6(#7=s#8)
Steaton
  • 119
  • 1
  • 6