java 获取接口的注解_java – 从类中获取接口注释方法

本文探讨了如何使用Java反射机制访问接口中带有特定注释的方法,特别是当这些方法被Spring框架注入到实现类中时。介绍了遍历方法及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我想通过反射访问Method.问题是Method在界面中注释:

public interface MyRepository extends CrudRepository {

@CustomAnnotation

MyClass findByName(String name);

}

如您所见,我使用Spring提供了一个实现此Repository接口的类.

我想创建一个方法,它将获得一个Repository并调用所有使用@CustomAnnotation注释的方法.

public void do(Repository, ?> repository){

Method[] methods=repository.getClass().getMethodThatAreAnnotatedInInterfaceWith(CustomAnnotation.class);

....

}

因为接口的实现不会出现接口的注释,所以我不知道如何查询这些方法.

解决方法:

Find a single Annotation of annotationType on the supplied Method, traversing its super methods (i.e., from superclasses and interfaces) if the annotation is not directly present on the given method itself.

迭代getClass().get [Declared] Methods()的方法,并为每个方法检查是否使用上述实用程序使用注释进行注释.

标签:java,reflection,spring

来源: https://codeday.me/bug/20190528/1167896.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值