如何使用java注解
Java注解的基本概念
Java注解(Annotation)是一种元数据形式,提供与程序元素(类、方法、变量等)关联的附加信息。注解本身不影响代码逻辑,但可以通过反射或编译时处理工具(如APT)实现特定功能。
定义自定义注解
通过@interface关键字定义注解,并可通过元注解(如@Target、@Retention)指定其使用范围和生命周期。
import java.lang.annotation.*;
@Target(ElementType.METHOD) // 注解作用于方法
@Retention(RetentionPolicy.RUNTIME) // 注解在运行时保留
public @interface CustomAnnotation {
String value() default "default"; // 可定义属性及默认值
int priority() default 1;
}
使用注解
将注解应用于类、方法或字段:
public class Example {
@CustomAnnotation(value = "test", priority = 2)
public void annotatedMethod() {
System.out.println("Method with annotation");
}
}
处理注解
通过反射机制读取运行时注解信息:
import java.lang.reflect.Method;
public class AnnotationProcessor {
public static void main(String[] args) throws Exception {
Method method = Example.class.getMethod("annotatedMethod");
CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);
if (annotation != null) {
System.out.println("Value: " + annotation.value());
System.out.println("Priority: " + annotation.priority());
}
}
}
常见元注解
@Target:指定注解适用的目标(如ElementType.TYPE用于类)。@Retention:定义注解保留策略(SOURCE、CLASS、RUNTIME)。@Documented:将注解包含在Javadoc中。@Inherited:允许子类继承父类的注解。
编译时处理
通过javax.annotation.processing.Processor接口实现编译时注解处理,生成代码或验证逻辑。需搭配@SupportedAnnotationTypes和@SupportedSourceVersion使用。

内置注解示例
@Override:标记方法重写父类方法。@Deprecated:标识已过时的元素。@SuppressWarnings:抑制编译器警告。
注意事项
- 注解属性必须是常量表达式,且不能为
null。 - 若属性名为
value且是唯一属性,使用时可直接赋值(如@Annotation("data"))。 - 运行时处理的注解需搭配反射,可能影响性能。






