17.Java 注解与实例
17.Java 注解与实例
什么是注解
注解(Annotation)是 Java 5 引入的一种元数据(metadata)机制,它为代码提供附加信息,但不直接影响代码逻辑。注解可以用于:
- 编译时检查(如
@Override
) - 运行时处理(如框架配置)
- 代码生成工具(如 Lombok)
元注解
元注解是用于注解其他注解的注解。Java 提供了四个标准的元注解:
-
@Retention
- 指定注解的保留策略SOURCE
:仅保留在源码中,编译时丢弃CLASS
:保留在字节码中,但运行时不可见(默认)RUNTIME
:保留在运行时,可通过反射获取
-
@Target
- 指定注解可以应用的目标TYPE
:类、接口、枚举FIELD
:字段METHOD
:方法PARAMETER
:参数CONSTRUCTOR
:构造方法LOCAL_VARIABLE
:局部变量ANNOTATION_TYPE
:注解类型PACKAGE
:包
-
@Documented
- 指示注解应包含在 Javadoc 中 -
@Inherited
- 指示子类可以继承父类的注解
自定义注解实例
下面我们将创建一个完整的自定义注解示例,包括元注解的使用和运行时反射处理。
1. 定义自定义注解
package com.example.annotation;import java.lang.annotation.*;/*** 自定义注解示例** @Retention(RetentionPolicy.RUNTIME) - 注解在运行时保留,可通过反射获取* @Target({ElementType.METHOD, ElementType.TYPE}) - 可用于方法和类* @Documented - 包含在Javadoc中*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
public @interface MyAnnotation {// 注解属性(类似接口中的抽象方法)String value() default ""; // 默认值为空字符串int priority() default 1; // 默认优先级为1boolean enabled() default true; // 默认启用
}
2. 使用自定义注解
package com.example.annotation;
/*** 使用自定义注解的类** @MyAnnotation - 类级别的注解,使用默认值*/
@MyAnnotation
public class AnnotationDemo {private String name;/*** 使用自定义注解的方法** @MyAnnotation(value = "重要方法", priority = 2, enabled = true) - 方法级别的注解,指定了所有属性*/@MyAnnotation(value = "重要方法", priority = 2, enabled = true)public void doSomething(String param) {System.out.println("执行操作,参数: " + param);this.name = param;}/*** 未使用注解的方法*/public void doNothing() {System.out.println("什么也不做");}// Getter和Setterpublic String getName() {return name;}public void setName(String name) {this.name = name;}
}
3. 通过反射处理注解
package com.example.processor;import com.example.annotation.AnnotationDemo;
import com.example.annotation.MyAnnotation;import java.lang.reflect.Method;public class AnnotationProcessor {public static void main(String[] args) {// 获取AnnotationDemo类的Class对象Class<AnnotationDemo> demoClass = AnnotationDemo.class;// 1. 处理类级别的注解if (demoClass.isAnnotationPresent(MyAnnotation.class)) {MyAnnotation classAnnotation = demoClass.getAnnotation(MyAnnotation.class);System.out.println("类注解信息:");System.out.println(" 值: " + classAnnotation.value());System.out.println(" 优先级: " + classAnnotation.priority());System.out.println(" 是否启用: " + classAnnotation.enabled());}System.out.println("\n方法注解信息:");// 2. 处理方法级别的注解Method[] methods = demoClass.getDeclaredMethods();for (Method method : methods) {if (method.isAnnotationPresent(MyAnnotation.class)) {MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);System.out.println("方法: " + method.getName());System.out.println(" 值: " + methodAnnotation.value());System.out.println(" 优先级: " + methodAnnotation.priority());System.out.println(" 是否启用: " + methodAnnotation.enabled());// 如果方法有参数,可以进一步处理参数注解(本例中方法没有参数注解)// Class<?>[] parameterTypes = method.getParameterTypes();// Annotation[][] parameterAnnotations = method.getParameterAnnotations();}}}
}
4. 运行结果
运行 AnnotationProcessor
类,输出结果如下: