Introspect Scala traits

北战南征 提交于 2019-12-11 10:57:04

问题


Consider the example

class FooListener extends Listener {
  @Listen
  def runMeToo = {
    ...
  }
}

trait Listener {

  @Listen
  def runMe = {
    ...
  }
}

I'm writing introspection code to find all methods of a given class (ie FooListener) annotated with a certain annotation (ie @Listen). They'll be invoked under certain circumstances. So I need all their java.lang.Method instances.

It's easy to find those methods in the FooListener class. Easy also to find those of the super classes.

The question is how to find those inherited from the traits ? And the traits of the traits ? Etc...


回答1:


Methods inherited from a trait are just copied into the class. So you can find them by just listing the methods of the class.

val ms = classOf[FooListener].getMethods()

And then print them with their annotations.

ms.foreach(m => m.getDeclaredAnnotations().foreach(a => println(m + " " + a)))

In my case (annotated with Test), this prints

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)



回答2:


Since traits are translated to interfaces in Java, the following code snippet should work:

val methods = classOf[FooListener].getInterfaces flatMap {intf =>
    intf.getMethods filter {_.getAnnotation(classOf[Listen]) != null}
}


来源:https://stackoverflow.com/questions/13101235/introspect-scala-traits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!