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

问题描述 投票:0回答:3

java.lang.annotation.ElementType

程序元素类型。此枚举类型的常量提供了 Java 程序中声明的元素的简单分类。这些常量与

Target
元注释类型 一起使用,以指定在何处使用注释类型是合法的。

有以下常数:

  • ANNOTATION_TYPE - 注释类型声明
  • CONSTRUCTOR - 构造函数声明
  • FIELD - 字段声明(包括枚举常量)
  • LOCAL_VARIABLE - 局部变量声明
  • METHOD - 方法声明
  • 包装 - 包装声明
  • PARAMETER - 参数声明
  • TYPE - 类、接口(包括注释类型)或枚举声明
有人可以解释一下它们分别是什么(它们在实际代码中的注释位置)吗?

java annotations
3个回答
122
投票
假设您指定

ElementType

 的注释称为 
YourAnnotation
:

  • ANNOTATION_TYPE - 注释类型声明。

    注意: 这也适用于其他注释

    @YourAnnotation public @interface AnotherAnnotation {..}
    
    
  • CONSTRUCTOR - 构造函数声明

    public class SomeClass { @YourAnnotation public SomeClass() {..} }
    
    
  • FIELD - 字段声明(包括枚举常量)

    @YourAnnotation private String someField;
    
    
  • LOCAL_VARIABLE - 局部变量声明。

    注意: 这无法在运行时读取,因此它仅用于编译时的事情,例如 @SuppressWarnings

     注释。

    public void someMethod() { @YourAnnotation int a = 0; }
    
    
  • 方法 - 方法声明

    @YourAnnotation public void someMethod() {..}
    
    
  • 包装 - 包装声明。

    注意: 只能在package-info.java

    中使用。

    @YourAnnotation package org.yourcompany.somepackage;
    
    
  • 参数 - 参数声明

    public void someMethod(@YourAnnotation param) {..}
    
    
  • TYPE - 类、接口(包括注释类型)或枚举声明

    @YourAnnotation public class SomeClass {..}
    
    
您可以为给定注释指定多个

ElementType

。例如:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
    

65
投票
总结了主要内容:

@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; } }

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

@CustomAnnotationTypeAnnotation public @interface SomeAnnotation { .. }

Package 是在包中的

package-info.java

 文件中定义的,如下所示:

@CustomPackageLevelAnnotation package com.some.package; import com.some.package.annotation.PackageLevelAnnotation;

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

此处此处


4
投票

类型

注释:

@Target({ElementType.TYPE}) // This annotation can only be applied to public @interface Tweezable { // class, interface, or enum declarations. }

以及示例用法:

@Tweezable public class Hair { ... }
    
© www.soinside.com 2019 - 2024. All rights reserved.