内省Scala特征 [英] Introspect Scala traits

查看:112
本文介绍了内省Scala特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑示例

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

trait Listener {

  @Listen
  def runMe = {
    ...
  }
}

我正在编写自省代码,以查找带有特定注释(即 @Listen )的给定类(即 FooListener )的所有方法.在某些情况下会调用它们.因此,我需要他们所有的 java.lang.Method 实例.

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.

在FooListener类中很容易找到那些方法.容易也找到那些超级类.

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...

推荐答案

从特征继承的方法只是复制到该类中.因此,您只需列出类的方法即可找到它们.

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)))

在我的情况下(用Test注释),此打印内容

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)

这篇关于内省Scala特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆