在 Java 中,自定义注解(Annotation)主要用于为代码提供元数据,常与反射、编译期处理或框架结合使用。下面从基本定义 → 元注解 → 成员变量 → 使用方式 → 运行时读取逐步说明。
public @interface MyAnnotation {
}
使用:
@MyAnnotation
public class Test {
}
Java 提供了 4 个元注解来控制注解的行为:
@Target(ElementType.METHOD)
常见取值:
TYPE(类、接口)METHOD(方法)FIELD(字段)PARAMETER(参数)CONSTRUCTORLOCAL_VARIABLE示例:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
三种策略:
SOURCE:仅存在于源码(编译后丢弃)CLASS:保留到 .class 文件(默认)RUNTIME:运行时可用(最常用,可反射读取)@Documented
@Inherited
只对类有效,不对方法、字段有效。
注解中的“变量”其实是方法形式:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
int count() default 1;
}
使用:
@MyAnnotation(value = "hello", count = 3)
public void test() {
}
如果只有一个 value(),可省略名字:
@MyAnnotation("hello")
Method method = Test.class.getMethod("test");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
if (annotation != null) {
System.out.println(annotation.value());
System.out.println(annotation.count());
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
public class Service {
@Log("查询用户")
public void query() {}
}
for (Method m : Service.class.getMethods()) {
if (m.isAnnotationPresent(Log.class)) {
Log log = m.getAnnotation(Log.class);
System.out.println(m.getName() + " -> " + log.value());
}
}
@RequiresPermission)如果你需要:
可以告诉我具体方向,我可以进一步举例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。