首页 > 解决方案 > 反射获取特定类中带注释的所有方法

问题描述

我正在编写一个事件消息处理程序。为了处理反射,我使用了 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)
}

但是,在注册监听器时,对象被保存在元组中,但没有任何方法,有人知道为什么吗?

标签: javascalareflection

解决方案


通过做解决

@Retention(RetentionPolicy.RUNTIME)
public @interface ListenTo

对于其他任何由此而来的人。


推荐阅读