java如何获取方法上的注解

1713
2023/8/28 17:34:39
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要获取方法上的注解,可以使用Java的反射机制。以下是一种常见的方法:

  1. 首先,使用Class类的getMethodgetDeclaredMethod方法获取要获取注解的方法。getMethod方法可以获取公共方法,而getDeclaredMethod方法可以获取所有方法,包括私有方法。
Class<?> clazz = MyClass.class;
Method method = clazz.getDeclaredMethod("myMethod");
  1. 然后,使用Method类的getAnnotation方法获取方法上的注解。getAnnotation方法接收一个注解的类型作为参数,并返回该注解的实例。如果方法上没有该注解,getAnnotation方法将返回null
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
  1. 最后,可以通过注解对象的方法来获取注解的属性值。
String value = annotation.value();

完整的示例代码如下:

import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value();
}
class MyClass {
@MyAnnotation("Hello")
public void myMethod() {
// 方法体
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Class<?> clazz = MyClass.class;
Method method = clazz.getDeclaredMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value();
System.out.println(value); // 输出:Hello
}
}

需要注意的是,注解的保留策略需要设置为RetentionPolicy.RUNTIME,才能在运行时通过反射获取到注解。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java log4j2与SLF4J集成方法