java.lang.annotation.ElementType
:
程序元素类型。此枚举类型的常量提供了 Java 程序中声明的元素的简单分类。这些常量与
Target
元注释类型 一起使用,以指定在何处使用注释类型是合法的。
有以下常数:
ElementType
的注释称为
YourAnnotation
:
注意: 这也适用于其他注释
@YourAnnotation
public @interface AnotherAnnotation {..}
public class SomeClass {
@YourAnnotation
public SomeClass() {..}
}
@YourAnnotation
private String someField;
注意: 这无法在运行时读取,因此它仅用于编译时的事情,例如 @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) {..}
@YourAnnotation
public class SomeClass {..}
ElementType
。例如:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@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 注释的更多信息,请参阅
类型:
注释:
@Target({ElementType.TYPE}) // This annotation can only be applied to
public @interface Tweezable { // class, interface, or enum declarations.
}
以及示例用法:
@Tweezable
public class Hair {
...
}