-1

如果它定义了以下注释:

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();
}

然后使用它定义以下接口:

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

如果我然后运行以下命令:

javac MyClass.java

javap MyClass.class

然后我的输出是:

编译自“MyClass.java”

公共接口 MyClass { }

所以在我看来,注释没有被保留?如果是这样,为什么会这样?

4

2 回答 2

1

使用-v/-verbose选项打印附加信息

> javap -c -v MyClass.class 

[...]

SourceFile: "MyClass.java"
RuntimeVisibleAnnotations:
  0: #24(#25=s#26)
    org.example.MyAnnot(
      value="somevalue"
    )
于 2018-09-12T15:28:35.703 回答
-1

如果您看到以下内容,您会注意到它确实保留了注释。只是 javap 没有在标准输出中显示它。使用详细的 -v 选项确实显示它:

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)
于 2018-09-12T15:35:36.757 回答