在 Java 中,自定义注解(Annotation)是通过 @interface 关键字来定义的,并结合元注解来规定注解的使用范围和生命周期。下面从基础到进阶给你讲清楚。
public @interface MyAnnotation {
}
使用方式:
@MyAnnotation
public class Test {
}
但这只是“标记”,通常没什么实际作用。
public @interface MyAnnotation {
String value();
int count() default 1;
}
使用:
@MyAnnotation(value = "hello", count = 3)
public class Test {
}
如果只有一个 value(),可以省略名字:
@MyAnnotation("hello")
@Target:注解能用在哪里import java.lang.annotation.*;
@Target(ElementType.METHOD)
public @interface MyAnnotation {
}
常见取值:
TYPE(类、接口)METHOD(方法)FIELD(字段)PARAMETER(参数)CONSTRUCTOR(构造方法)可以多个:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention:注解保留到什么时候@Retention(RetentionPolicy.RUNTIME)
三种策略:
SOURCE:只在源码中,编译后丢弃(如 @Override)CLASS:编译进 class 文件,但运行时不可见RUNTIME:运行时可通过反射获取(最常用)@Documented:是否生成到 JavaDoc@Documented
@Inherited:是否允许子类继承@Inherited
只对类有效,对方法无效。
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
使用:
public class UserService {
@Log("用户登录")
public void login() {
}
}
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
Method method = UserService.class.getMethod("login");
if (method.isAnnotationPresent(Log.class)) {
Log log = method.getAnnotation(Log.class);
System.out.println(log.value());
}
}
}
@RequiresPermission)@Log)@RateLimit)@NotNull)如果你愿意,我也可以给你讲:
你想深入哪一块?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。