在 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")
Java 提供了 5 个常用元注解:
@Target指定注解可以用在哪里(类、方法、字段等)
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MyAnnotation {
}
常见取值:
TYPE:类、接口METHOD:方法FIELD:字段PARAMETER:参数CONSTRUCTOR:构造方法@Retention指定注解的生命周期
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
取值:
SOURCE:源码阶段(如 @Override)CLASS:字节码阶段(默认)RUNTIME:运行时(可通过反射读取)✅ 最常用@Documented注解是否包含在 JavaDoc 中
@Documented
public @interface MyAnnotation {
}
@Inherited子类是否继承父类的注解
@Inherited
public @interface MyAnnotation {
}
@Repeatable(Java 8+)允许注解重复使用
@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {
String value();
}
public @interface MyAnnotations {
MyAnnotation[] value();
}
使用:
@MyAnnotation("a")
@MyAnnotation("b")
public class Test {
}
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
使用 + 反射读取:
public class Test {
@Log("测试方法")
public void test() {}
public static void main(String[] args) throws Exception {
Method m = Test.class.getMethod("test");
if (m.isAnnotationPresent(Log.class)) {
Log log = m.getAnnotation(Log.class);
System.out.println(log.value());
}
}
}
@interface 定义注解RUNTIME + 反射 才能读取注解如果你是想了解Spring 注解 / 自定义校验注解 / 编译期注解,也可以继续问我。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。