Java注释ElementType常量是什么意思?

Act*_*son 55 java annotations

java.lang.annotation.ElementType:

程序元素类型.此枚举类型的常量提供Java程序中声明的元素的简单分类.这些常量与Target元注释类型一起使用,以指定使用注释类型的合法位置.

有以下常量:

  • ANNOTATION_TYPE - 注释类型声明
  • CONSTRUCTOR - 构造函数声明
  • FIELD - 字段声明(包括枚举常量)
  • LOCAL_VARIABLE - 局部变量声明
  • 方法 - 方法声明
  • 包装 -包装声明
  • PARAMETER - 参数声明
  • TYPE - 类,接口(包括注释类型)或枚举声明

有人可以解释它们中的每一个(在实际代码中它们会被注释)吗?

Boz*_*zho 96

假设您指定的注释ElementType被称为YourAnnotation:

您可以ElementType为给定的注释指定多个s.例如:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
Run Code Online (Sandbox Code Playgroud)

  • `@Bozho:`感谢您的专业提示。我在投票计数器下面的东西上打了勾。 (2认同)

Jav*_*mae 50

这总结了主要的:

@CustomTypeAnnotation
public class MyAnnotatedClass {
  @CustomFieldAnnotation
  private String foo;

  @CustomConstructorAnnotation
  public MyAnnotatedClass() {
  }

  @CustomMethodAnnotation
  public String bar(@CustomParameterAnnotation String str) {
    @CustomLocalVariableAnnotation String asdf = "asdf";
    return asdf + str;
  }
}
Run Code Online (Sandbox Code Playgroud)

ANNOTATION_TYPE是另一个注释的注释,如下所示:

@CustomAnnotationTypeAnnotation
public @interface SomeAnnotation {
  ..
}
Run Code Online (Sandbox Code Playgroud)

package-info.java在包中的文件中定义,如下所示:

@CustomPackageLevelAnnotation
package com.some.package;

import com.some.package.annotation.PackageLevelAnnotation;
Run Code Online (Sandbox Code Playgroud)

有关PACKAGE注释的更多信息,请参阅此处此处.

  • 如果你还包括ANNOTATION_TYPE和PACKAGE的片段,答案会更好. (4认同)
  • @JohnGlassmyer - 晚了几年,但我为 ANNOTATION_TYPE 和 PACKAGE 添加了更多片段。:-) (3认同)