如何使用注解java
使用注解的基本概念
Java 注解(Annotation)是一种元数据形式,用于为代码提供附加信息。注解不会直接影响代码逻辑,但可以通过反射或编译器处理实现特定功能。
定义自定义注解
通过 @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");
if (method.isAnnotationPresent(CustomAnnotation.class)) {
CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);
System.out.println("Value: " + annotation.value());
System.out.println("Priority: " + annotation.priority());
}
}
}
常见内置注解
@Override:标记方法重写父类方法。@Deprecated:标记已过时的代码。@SuppressWarnings:抑制编译器警告。
注解的进阶用法
- 编译时处理:通过注解处理器(APT)在编译时生成代码(需配合
javac -processor使用)。 - 框架集成:Spring 的
@Autowired、JUnit 的@Test等均依赖注解实现功能。
通过合理使用注解,可以提升代码的可读性和可维护性,同时支持框架的自动化处理。






