java注解如何使用
注解的基本概念
注解(Annotation)是Java 5引入的一种元数据机制,用于为代码添加标记信息。注解本身不影响程序逻辑,但可以通过反射或编译器处理实现特定功能(如生成代码、配置依赖等)。
定义注解
通过 @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:抑制编译器警告(如"unchecked")。
元注解
用于修饰其他注解的注解:

@Target:指定注解可应用的目标(如ElementType.TYPE用于类)。@Retention:定义注解保留策略(SOURCE、CLASS、RUNTIME)。@Inherited:允许子类继承父类的注解。
注解的典型应用场景
- 框架配置:如Spring的
@Autowired、JPA的@Entity。 - 代码生成:Lombok的
@Getter在编译时生成getter方法。 - 测试:JUnit的
@Test标记测试方法。
通过合理使用注解,可以显著减少样板代码,提升代码可读性和维护性。






