一、自定义注解
用 @interface 定义,配合元注解指定作用范围与保留期:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
二、读取注解(反射)
Method m = obj.getClass().getMethod("foo");
if (m.isAnnotationPresent(Log.class)) {
Log log = m.getAnnotation(Log.class);
System.out.println(log.value());
}
三、用途
- 框架配置:Spring 的
@Controller、@Autowired; - 横切逻辑:自定义
@Log做日志、@RateLimit做限流; - 校验:Bean Validation 的
@NotNull。
注解本身不做事,靠”读取方”赋予能力,是声明式编程的基础。