介绍:在Java中,自定义注解是通过 @interface
关键字定义的。注解是一种元数据,可以附加到类、方法、字段等代码元素上,用于提供额外的信息或配置。
1. 自定义注解的基本语法
使用 @interface
关键字定义注解,注解中可以包含成员变量(称为注解属性)。下面是一个简单示例:
import java.lang.annotation.*;
// 定义一个注解
@Retention(RetentionPolicy.RUNTIME) // 注解在运行时保留
//@Target(ElementType.METHOD) // 注解只能用于方法
public @interface MyAnnotation {
String name(); // 必须提供的属性
int version() default 1; // 可选属性,默认值为 1
String[] tags() default {}; // 数组属性
}
//使用注解
@MyAnnotation(name = "TestClass", version = 2, tags = {"java", "annotation"})
public class MyClass {
@MyAnnotation(name = "testMethod")
public void myMethod() {
System.out.println("Executing myMethod");
}
}
元注解
元注解是用来修饰注解的注解。Java 提供了以下常用的元注解&#