1

I've been searching for a while and can't seem to find something that matches exactly what I need.

I want to have a way to wrap any class (let's say T) with something that would "do something cool" before and after each invocation of the public methods of this T class, and this thing would look like T to the compiler.

Here's some pseudo code to illustrate:

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

Using reflection is not out of the question, this would only happen once per instance that would live in memory throughout the life of the process, so I'm not concerned with it being slow to instantiate.

Is this even possible? (currently forced to use Scala 2.9.2)

Thanks!

Enrico
  • 621
  • 1
  • 4
  • 12
  • 3
    What you're looking for is called Aspect oriented programming. Commonly in Java it would be done with Spring AOP or AspectJ or something similar. Alternatively, you can use a [DynamicProxy](http://lampwww.epfl.ch/~hmiller/scaladoc/library/scala/reflect/DynamicProxy.html) but that would have to actually be dynamic and would give you no compile time information. – Benjamin Gruenbaum Mar 23 '14 at 02:19
  • Looks like there might be some guidance in [this SO answer](http://stackoverflow.com/questions/5025700/can-i-do-aspect-oriented-programming-in-scala). – wwkudu Mar 23 '14 at 05:29

0 Answers0