考虑一下这个例子
class FooListener extends Listener {
@Listen
def runMeToo = {
...
}
}
trait Listener {
@Listen
def runMe = {
...
}
}我正在编写内省代码,以查找给定类的所有方法(即、FooListener、),并使用特定的注释(即@Listen)进行注释。在某些情况下他们会被调用。所以我需要他们所有的java.lang.Method实例。
在FooListener类中很容易找到这些方法。也很容易找到那些超类。
问题是如何找到从这些特征中继承下来的?以及这些特征的特征?等等..。
发布于 2012-10-27 15:03:04
从特征继承的方法被复制到类中。所以只需列出类的方法就可以找到它们。
val ms = classOf[FooListener].getMethods()然后用注解打印出来。
ms.foreach(m => m.getDeclaredAnnotations().foreach(a => println(m + " " + a)))在我的例子中(用Test注释),这个输出
public void util.FooListener.runMe() @org.junit.Test(expected=class org.junit.Test$None, timeout=0)
public void util.FooListener.runMeToo() @org.junit.Test(expected=class org.junit.Test$None, timeout=0)发布于 2012-10-27 15:05:34
由于特性在Java中被转换为接口,下面的代码片段应该可以工作:
val methods = classOf[FooListener].getInterfaces flatMap {intf =>
intf.getMethods filter {_.getAnnotation(classOf[Listen]) != null}
}https://stackoverflow.com/questions/13101235
复制相似问题