java如何定义注解
定义注解的基本语法
在Java中,注解通过@interface关键字定义。注解可以包含元素(类似方法),这些元素可以有默认值。
public @interface MyAnnotation {
String value() default "default";
int count() default 0;
}
元注解的使用
元注解用于修饰其他注解,控制注解的行为。常用的元注解包括:

@Retention:指定注解的保留策略(SOURCE、CLASS、RUNTIME)@Target:指定注解可以应用的目标(TYPE、FIELD、METHOD等)@Documented:指示注解应包含在Javadoc中@Inherited:允许子类继承父类的注解
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestMethod {
String description();
boolean enabled() default true;
}
注解元素类型限制
注解元素支持的类型有限制,允许的类型包括:
- 基本数据类型(int、float等)
- String
- Class
- 枚举类型
- 注解类型
- 以上类型的数组
public @interface ComplexAnnotation {
Class<?> targetClass();
Priority priority() default Priority.MEDIUM;
String[] tags();
}
enum Priority {
HIGH, MEDIUM, LOW
}
使用自定义注解
定义好的注解可以像内置注解一样使用:

@TestMethod(description = "Sample test", enabled = false)
public void testFeature() {
// 测试代码
}
运行时处理注解
通过反射可以在运行时访问注解信息:
Method method = obj.getClass().getMethod("testFeature");
if (method.isAnnotationPresent(TestMethod.class)) {
TestMethod testMethod = method.getAnnotation(TestMethod.class);
System.out.println(testMethod.description());
}
注解的默认值
注解元素可以指定默认值,使用时可以省略有默认值的元素:
public @interface DefaultValueAnnotation {
String name() default "unnamed";
int version() default 1;
}
// 使用时可只指定部分值
@DefaultValueAnnotation(name = "special")
public class SampleClass {}






