为什么注释没有保留在 class 文件中
Why is annotation not retained in class file
如果定义了如下注解:
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
那么我的输出是:
Compiled from "MyClass.java"
public interface MyClass { }
所以在我看来注释没有被保留?如果是这样,为什么会这样?
使用-v
/-verbose
选项打印附加信息
> javap -c -v MyClass.class
[...]
SourceFile: "MyClass.java"
RuntimeVisibleAnnotations:
0: #24(#25=s#26)
org.example.MyAnnot(
value="somevalue"
)
如果您看到以下内容,您会注意到它实际上保留了注释。只是 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)
如果定义了如下注解:
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
那么我的输出是:
Compiled from "MyClass.java"
public interface MyClass { }
所以在我看来注释没有被保留?如果是这样,为什么会这样?
使用-v
/-verbose
选项打印附加信息
> javap -c -v MyClass.class
[...]
SourceFile: "MyClass.java"
RuntimeVisibleAnnotations:
0: #24(#25=s#26)
org.example.MyAnnot(
value="somevalue"
)
如果您看到以下内容,您会注意到它实际上保留了注释。只是 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)