在 Java 中,注解(Annotation) 是一种用于为代码添加元数据的机制,它不会直接影响代码逻辑,但可以被编译器、开发工具或运行时框架读取和使用。
预定义的注解
@Override
标记方法重写父类方法,编译器会检查方法签名是否正确。
@Override public void toString() { ... }
@Deprecated
标记方法或类已过时,使用时编译器会警告。
@Deprecated public void oldMethod() { ... }
@FunctionalInterface
(Java 8+)
标记接口为函数式接口(只能有一个抽象方法)。
@FunctionalInterface public interface MyFunction { void apply(); }
自定义注解
通过 @interface
关键字定义注解:
1. 定义注解
// 元注解(定义注解的元数据) @Target(ElementType.METHOD) // 注解可作用在方法上 @Retention(RetentionPolicy.RUNTIME) // 注解保留到运行时 public @interface MyAnnotation { String value() default "default value"; // 注解属性 int priority() default 1; }
2. 元注解(Meta-Annotation)
控制注解行为的注解:
-
@Target
:指定注解可应用的位置(类、方法、字段等)。
可选值:ElementType.TYPE
,METHOD
,FIELD
,PARAMETER
等。 -
@Retention
:指定注解保留的周期。
可选值:-
SOURCE
:仅源码保留(如@Override
) -
CLASS
:保留到字节码(默认) -
RUNTIME
:运行时可通过反射读取(常用)
-
-
@Documented
:注解包含在 Javadoc 中。 -
@Inherited
:子类可继承父类的注解。 -
三、使用注解
-
直接在代码目标位置标注注解:
-
public class MyClass { @MyAnnotation(value = "test", priority = 2) public void myMethod() { ... } }
-
四、处理注解(反射)
通过反射在运行时读取注解信息:
Method method = MyClass.class.getMethod("myMethod"); if (method.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); System.out.println(annotation.value()); // 输出 "test" System.out.println(annotation.priority()); // 输出 2 }