围绕Scala中任何给定类的方法动态创建代理

时间:2014-03-23 02:04:32

标签: scala

我一直在寻找一段时间,似乎无法找到与我需要的完全匹配的东西。

我希望有一种方法可以在每次调用此T类的公共方法之前和之后,将任何类(让我们说T)包装起来“做一些很酷的事情”。对于编译器来说,事情看起来就好了。

这里有一些伪代码来说明:

object CoolWrap {
  def apply[T](underlying: T) {
    new CoolWrapImpl(underlying).asInstanceOf[T]
  }
}

class CoolWrapImpl[T](underlying: T) extends T {

  def onPublicMethod(method: Method, params: Params) = {
    // method would be the method that was invoked on T
    doSomethingCool1(params) // like logging
    val resp = measureTime { method.invoke(params) }
    doAnotherCoolThing()
    resp
  }
}

使用反射并不是不可能的,这只会发生在整个过程生命周期中存在于内存中的每个实例一次,所以我并不担心它实例化的速度很慢。

这甚至可能吗? (目前被迫使用Scala 2.9.2)

谢谢!

0 个答案:

没有答案