java - 在注释声明中定义枚举和字段是什么意思?

标签 java

似乎可以在 Java 中的注释声明中声明字段和枚举。例如,javac 编译这个:

 @interface ClassPreamble {
   public enum AnEnum {
        Value;
   }
   String aField = "";

   String author();
   String date();
   String currentRevision() default "";
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

在注释声明中定义枚举和字段的意义/用途是什么?

谢谢

最佳答案

Java注解只是继承了java.lang.annotation.Annotation(*)的接口(interface),在一定程度上被编译器特殊对待,但编译器不会阻止你做什么在接口(interface)内是合法的。它甚至可能很有用(请参阅此答案底部来自 JLS 的示例)。

(*) 虽然手动扩展Annotation 的接口(interface)没有定义注释类型(来源:javadoc for Annotation.java)

你的注释 ClassPreamble 实际上是 interface ClassPreamble extends java.lang.annotation.Annotation (反编译看看)。

在接口(interface)中声明枚举是合法的。 在接口(interface)中声明字段是合法的:它将隐式为 public static final。

$ cat Funny.java 
interface Funny {
  public enum AnEnum { One, Two }
  String aField = "";
}

$ javac Funny.java 

$ javap -c Funny.class
Compiled from "Funny.java"
interface Funny extends java.lang.annotation.Annotation {
  public static final java.lang.String aField;

}

$ javap -c Funny\$AnEnum.class | head
Compiled from "Funny.java"
public final class Funny$AnEnum extends java.lang.Enum<Funny$AnEnum> {
  public static final Funny$AnEnum One;

  public static final Funny$AnEnum Two;

  public static Funny$AnEnum[] values();
    Code:
       0: getstatic     #1                  // Field $VALUES:[LFunny$AnEnum;
       3: invokevirtual #2                  // Method "[LFunny$AnEnum;".clone:()Ljava/lang/Object;
...

对于“此类结构的含义是什么?”,我不确定是否有好的答案。我猜它是作为一种设计选择以这种方式实现的:注释所做的任何事情都被编码为接口(interface)的字节码,JVM 知道如何处理,因此他们不需要对 JVM 本身进行过多修改(如果有的话) , 它允许编译时和运行时所需的功能,并且它不会造成伤害(或者会造成伤害吗?)。

编辑:2 节摘自 Java Language Specification section 9.6 about annotations (属于关于接口(interface)的第9章):

An annotation type declaration specifies a new annotation type, a special kind of interface type. To distinguish an annotation type declaration from a normal interface declaration, the keyword interface is preceded by an at-sign (@).

[...]

The grammar for annotation type declarations permits other element declarations besides method declarations. For example, one might choose to declare a nested enum for use in conjunction with an annotation type:

@interface Quality {
    enum Level { BAD, INDIFFERENT, GOOD }
    Level value();
}

关于java - 在注释声明中定义枚举和字段是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458571/

相关文章:

Java:如何将 List<?> 转换为 Map<String,?>

java - MessageDrivenBean 中的 Finalize 方法

java - 对有效的 XML 感到愤怒的 JAXB 解析器?

java - 使用 Junit 对边缘情况进行单元测试

Java 错误 : cannot find symbol: method join(java. lang.String,java.lang.String[])

java - 未分类的 SQLException Jdbc 模板

java - 代码从顺序到线程

java - 如何相交两组不适合内存的long?

Java 从单独的进程获取标准输出和标准错误

java - 我是 Spring Boot 新手,试图了解 Hibernate 映射,下面是我的代码