java - 反射获取特定类中带注释的所有方法
问题描述
我正在编写一个事件消息处理程序。为了处理反射,我使用了 Reflections API ( https://github.com/ronmamo/reflections )。
每个事件监听器都是一个方法注解
public @interface ListenTo {}
听众会遵循一个主题,例如:
class Example {
EventHandler.get.registerListener(this)
@ListenTo
def onEvent(e: SomeEvent): Unit
}
注册监听器的代码如下:
import org.reflections.ReflectionUtils._
private var listeners: mutable.ListBuffer[(Any, List[Method])] = ListBuffer()
def registerListener(obj: Any): Unit = {
listeners += Tuple2(obj, getAllMethods(obj.getClass, withAnnotation(classOf[ListenTo])).asScala.toList)
}
但是,在注册监听器时,对象被保存在元组中,但没有任何方法,有人知道为什么吗?
解决方案
通过做解决
@Retention(RetentionPolicy.RUNTIME)
public @interface ListenTo
对于其他任何由此而来的人。
推荐阅读
- architecture - 设计基于时间值触发事件的可扩展后端系统
- swift - 自定义集合视图布局:'无效参数不满足:self.supplementaryViewProvider'
- python - 尝试使用 Telethon 加入频道时出现值错误
- python - html消息的编码损坏
- mlr3 - 如何使用嵌套超参数优化在 mlr3 中测试我们的模型
- nginx - Nginx 和 Oauth2-proxy:使用 Google 登录后,重定向回 Oauth 登录页面
- python - 如何将子集数据框的更改应用于源数据框
- continuous-integration - 有没有办法在设置页面的 Github Actions 中设置非秘密环境变量?
- python - 如何使用 PIL 将文件夹中的多个图像裁剪为圆形?
- python - 检查二维列表中的列是否包含相同的值