// 定义一个自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义注解 @MyAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "default value";
}
// 使用自定义注解的类
public class AnnotationExample {
// 使用自定义注解标记方法
@MyAnnotation(value = "This is a custom annotation")
public void annotatedMethod() {
System.out.println("This method is annotated.");
}
// 反射读取注解信息
public static void main(String[] args) throws Exception {
AnnotationExample example = new AnnotationExample();
example.annotatedMethod();
// 获取方法上的注解
MyAnnotation annotation = AnnotationExample.class.getMethod("annotatedMethod").getAnnotation(MyAnnotation.class);
if (annotation != null) {
System.out.println("Annotation value: " + annotation.value());
}
}
}
自定义注解:我们使用 @interface 关键字定义了一个名为 MyAnnotation 的注解。通过 @Retention 和 @Target 来指定注解的生命周期和应用范围。
@Retention(RetentionPolicy.RUNTIME) 表示该注解在运行时可见,可以通过反射获取。@Target(ElementType.METHOD) 表示该注解只能用于方法上。使用注解:在 AnnotationExample 类中,我们使用 @MyAnnotation 注解标记了 annotatedMethod 方法,并传递了一个字符串参数 "This is a custom annotation"。
反射读取注解:在 main 方法中,我们通过反射机制获取 annotatedMethod 方法上的 MyAnnotation 注解,并打印出注解的值。
这个例子展示了如何定义、使用和读取自定义注解。
上一篇:java feign
下一篇:java mapper
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站