Java 注解(Annotations)是元数据形式的标记,可以添加到 Java 代码中,用于提供额外的信息。在编译时、运行时或通过工具使用这些注解,来影响程序的行为或生成文档。注解可以用于类、方法、字段、参数、局部变量、包等。
定义注解
要定义一个注解,可以使用 @interface
关键字。以下是一个简单的注解定义示例:
package com.example;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;// 定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {String value();int number() default 0;
}
注解元注解
-
@Target
:指定注解可以应用的程序元素。可选值包括:ElementType.TYPE
:类、接口(包括注解类型)、枚举。ElementType.FIELD
:字段(包括枚举常量)。ElementType.METHOD
:方法。ElementType.PARAMETER
&